code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from lxml import etree import datetime def xml_to_dict(root_or_str, strict=True): """ Converts `root_or_str` which can be parsed xml or a xml string to dict. """ root = root_or_str if isinstance(root, str): import xml.etree.cElementTree as ElementTree root = ElementTree.XML(root_or_str) return {root.tag: _from_xml(root, strict)} def dict_to_xml(dict_xml): """ Converts `dict_xml` which is a python dict to corresponding xml. """ return _to_xml(dict_xml) # Functions below this line are implementation details. # Unless you are changing code, don't bother reading. # The functions above constitute the user interface. def _to_xml(el): """ Converts `el` to its xml representation. """ val = None if isinstance(el, dict): val = _dict_to_xml(el) elif isinstance(el, bool): val = str(el).lower() else: val = el if val is None: val = 'null' return val def _extract_attrs(els): """ Extracts attributes from dictionary `els`. Attributes are keys which start with '@' """ if not isinstance(els, dict): return '' return ''.join(' %s="%s"' % (key[1:], value) for key, value in els.items() if key.startswith('@')) def _dict_to_xml(els): """ Converts `els` which is a python dict to corresponding xml. """ def process_content(tag, content): attrs = _extract_attrs(content) text = isinstance(content, dict) and content.get('#text', '') or '' return '<%s%s>%s%s</%s>' % (tag, attrs, _to_xml(content), text, tag) tags = [] for tag, content in els.items(): # Text and attributes if tag.startswith('@') or tag == '#text': continue elif isinstance(content, list): for el in content: tags.append(process_content(tag, el)) elif isinstance(content, dict): tags.append(process_content(tag, content)) else: tags.append('<%s>%s</%s>' % (tag, _to_xml(content), tag)) return ''.join(tags) def _str_to_datetime(date_str): try: val = datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ") except ValueError: val = date_str return val def _str_to_boolean(bool_str): if bool_str.lower() != 'false' and bool(bool_str): return True return False def _from_xml(el, strict): """ Extracts value of xml element element `el`. """ val = None # Parent node. if len(el): val = {} for e in el: tag = e.tag v = _from_xml(e, strict) if tag in val: # Multiple elements share this tag, make them a list if not isinstance(val[tag], list): val[tag] = [val[tag]] val[tag].append(v) else: # First element with this tag val[tag] = v # Simple node. else: attribs = el.items() # An element with attributes. if attribs and strict: val = dict(('@%s' % k, v) for k, v in dict(attribs).items()) if el.text: converted = _val_and_maybe_convert(el) val['#text'] = el.text if converted != el.text: val['#value'] = converted elif el.text: # An element with no subelements but text. val = _val_and_maybe_convert(el) elif attribs: val = dict(attribs) return val def _val_and_maybe_convert(el): """ Converts `el.text` if `el` has attribute `type` with valid value. """ text = el.text.strip() data_type = el.get('type') convertor = _val_and_maybe_convert.convertors.get(data_type) if convertor: return convertor(text) else: return text _val_and_maybe_convert.convertors = { 'boolean': _str_to_boolean, 'datetime': _str_to_datetime, 'integer': int } def read_file(file): with open(file) as f: data = f.read() data = bytes(bytearray(data, encoding='utf-8')) root = etree.XML(data) return xml_to_dict(root) def get_res(file): tmp = read_file(file) res = {} for i, item in enumerate(tmp['result']['security']): res[i] = [] for cmd in item['item']: res[i].append(cmd['cmd']) return res
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/xmltools.py
xmltools.py
import os import sys import traceback from pathlib import Path """ 路径类 命名规则: 第一个abs/rel 用来表示是获取绝对路径还是相对路径的 第二个开始表示该方法的作用/效果/含义 """ SYS: str = sys.platform def abs_cwd_base(path): """ 获取当前【进程工作目录】为基准开始的某个路径的绝对路径 """ pwd = os.getcwd() return os.path.join(pwd, path) def abs_cwd(): """进程工作目录""" return os.getcwd() def abs_file(): """ 获取调用此函数的文件的绝对路径 :return: """ return traceback.extract_stack()[-2].filename def abs_file_base(file, path=''): """ 获取当前【调用此函数的文件的上级目录】为基准开始的某个路径的绝对路径 :param file :请传入 __file__ :param path: 上级目录下的文件路径位置 :return: """ db_path = os.path.dirname(os.path.abspath(file)) return os.path.join(db_path, path) def abs_find_file(path, suffix): """ 寻找某个绝对路径下的某个文件,返回 :param path: 基准路径 :param suffix: 文件名 :return: 文件绝对路径 """ try: res = [os.path.join(root, file) for root, dirs, files in os.walk(path) for file in files if file.endswith(suffix)] if res and len(res) == 1: return res[0] else: return False except Exception: return False def abs_find_program(program): """ Protected method enabling the object to find the full path of a binary from its PATH environment variable. :param program: name of a binary for which the full path needs to be discovered. :return: the full path to the binary. :todo: add a default path list in case PATH is empty. """ __is_windows = (SYS == 'win32') split_char = ';' if __is_windows else ':' program = program + '.exe' if __is_windows else program paths = os.environ.get('PATH', '').split(split_char) for path in paths: if (os.path.exists(os.path.join(path, program)) and not os.path.isdir(os.path.join(path, program))): if not __is_windows: return os.path.join(path, program) else: return '\"' + os.path.join(path, program) + '\"' return None def abs_find_real_link(bath_path: str): """ 传入文件的绝对路径,返回文件的源文件的绝对路径 :param bath_path: :return: """ if os.path.islink(bath_path): real_link = os.readlink(bath_path) bath_path = os.path.abspath(os.path.dirname(bath_path)) path = os.path.join(bath_path, real_link) return abs_find_real_link(path) else: return bath_path def abs_folder_files(folder): result = [] folder = path(folder) assert folder.is_dir() for file in folder.iterdir(): result.append(str(file)) return result def safe_path(p): return p.replace('/', '\\') if SYS == 'win32' else p.replace('\\', '/') def path(p): return Path(p) def _combine_path(path_a, path_b): pass def gain_path_files(_path): files = list(list(os.walk(_path))[0])[2] return files
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/path.py
path.py
import struct import math def t01(data, length, pos): val = bytes(data[pos - 1]) return val, pos + 1 def t02(data, length, pos): if length > 16: raise Exception return auto_unpack('>' + str(length) + 'B', data, pos) def t04(data, length, pos): return auto_unpack(str(length) + 'c', data, pos) def t05(data, length, pos): return False, pos def t06(data, length, pos): def _decode_oid_component(enstr, epos): n = 0 while True: oc, epos = auto_unpack('B', enstr, epos) oc = int(oc) n = n * 128 + (0x7F & oc) if octet < 128: break return n, epos oid = {} last = pos + length - 1 if pos <= last: oid['smap'] = '\x06' octet, pos = auto_unpack('B', data, pos) octet = int(octet) oid[2] = math.fmod(octet, 40) octet = octet - oid[2] oid[1] = octet // 40 while pos <= last: c, pos = _decode_oid_component(data, pos) oid[len(oid) + 1] = c return oid, pos def t30(data, length, pos): seq = [] spos = 1 error = False sstr, new_pos = auto_unpack(str(length) + 'c', data, pos) while spos < length: try: new_seq, spos = decode(sstr, spos) except: new_seq = None error = True if not new_seq: break seq.append(new_seq) return seq, new_pos def t0A(data, length, pos): return t02(data, length, pos) decoder = { b'\x01': t01, b'\x02': t02, b'\x04': t04, b'\x05': t05, b'\x06': t06, b'\x30': t30, b'\x0A': t0A } def auto_unpack(fmt, data, pos=0): """自动计算unpack的大小并返回结果""" length = struct.calcsize(fmt) new_pos = pos + length result = struct.unpack(fmt, data[pos:new_pos]) is_all_byte = True for item in result: if not isinstance(item, bytes): is_all_byte = False if is_all_byte: return bytes.join(b'', result), new_pos else: return *result, new_pos def _decode_length(data, pos): length, new_pos = auto_unpack('B', data, pos) length = int(length) if length > 128: length = length - 128 c = 0 for i in range(length): c = c * 256 n, new_pos = auto_unpack('B', data, new_pos) c = c + int(n) length = c return length, new_pos def decode(data, pos=0): etype, new_pos = auto_unpack('c', data, pos) length, new_pos = _decode_length(data, new_pos) if etype in decoder: return decoder[etype](data, length, new_pos) else: return None, new_pos
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/asn1.py
asn1.py
import logging from pprint import pformat from threading import Thread from kombu import Connection, Consumer, Exchange, Queue, eventloop, Producer from kombu.pools import producers from amqp.exceptions import ConnectionForced from ..file import read_yaml logger = logging.getLogger(__name__) # priority_to_routing_key = { # 'high': 'hipri', # 'mid': 'midpri', # 'low': 'lopri', # } def pretty(obj): return pformat(obj, indent=4) class Broker: queue_attrs = ['queue_arguments', 'binding_arguments', 'consumer_arguments', 'durable', 'exclusive', 'auto_delete', 'no_ack', 'alias', 'bindings', 'no_declare', 'expires', 'message_ttl', 'max_length', 'max_length_bytes', 'max_priority'] exchange_attrs = ['arguments', 'durable', 'passive', 'auto_delete', 'delivery_mode', 'no_declare'] def __init__(self, broker_ip='localhost', port=5672, username=None, password=None, queue=None, routing_key=None, exchange=None, exchange_type=None, **kwargs): self.exchanges = {} self.queues = {} self.host = broker_ip self.port = port self.username = username self.password = password self.vhost = kwargs['vhost'] if 'vhost' in kwargs else '%2F' self.kwargs = kwargs if queue and routing_key and exchange_type and exchange: _exchange_attr = self._find_attr(self.exchange_attrs, self.kwargs) _queue_attr = self._find_attr(self.queue_attrs, self.kwargs) self.queue, self.exchange = self.add_conn(queue, routing_key, exchange_type, exchange, _queue_attr, _exchange_attr) self._conn = None def load(self, config_dict=None, config_path=None, enforce=True): config = {} if config_path: try: config.update(read_yaml(config_path, 'MQCONFIG')) except Exception as e: logger.error(e, exc_info=True) return elif config_dict: config.update(config_dict) else: return exchanges = config.pop('exchange') if 'exchange' in config else {} queues = config.pop('queue') if 'queue' in config else {} if enforce: self.__dict__.update(config) else: self.__dict__.update((k, v) for k, v in config.items() if (k not in self.__dict__) or v) for exchange in exchanges: self.add_exchange(**exchange) for queue in queues: self.add_queue(**queue) def _check(self): if not self.host: raise ValueError("broker: invalid ip.") if not self.username: raise ValueError("broker: invalid user.") if not self.password: raise ValueError("broker: invalid passwd.") def _find_attr(self, keys: list, target: dict): res = {} for key in target: if key in keys: res[key] = target[key] return res @property def amqp(self): if self.host and self.username and self.password: return 'amqp://{}:{}@{}:{}/{}'.format(self.username, self.password, self.host, self.port, self.vhost) else: raise def connection(self): if not self._conn: self._check() self._conn = Connection(self.amqp, **self.kwargs) return self._conn def add_exchange(self, **kwarg): #: By default messages sent to exchanges are persistent (delivery_mode=2), #: and queues and exchanges are durable. _name = kwarg['name'] _exchange = Exchange(**kwarg) self.exchanges[_name] = _exchange def add_queue(self, **kwarg): _name = kwarg['name'] if kwarg['exchange'] in self.exchanges: kwarg['exchange'] = self.exchanges[kwarg['exchange']] _queue = Queue(**kwarg) self.queues[_name] = _queue else: logger.error('不存在 {} 这个exchange'.format(kwarg['exchange'])) def add_conn(self, queue, routing_key, exchange_type, exchange, queue_attrs={}, exchange_attrs={}): _exchange = self.add_exchange(name=exchange, type=exchange_type, **exchange_attrs) _queue = self.add_queue(name=queue, exchange=exchange, routing_key=routing_key, **queue_attrs) self.exchanges[exchange] = _exchange self.queues[queue] = _queue return _queue, _exchange class RabbitMQ: def __init__(self, broker, cb=None): self.broker = broker self.cb = cb if cb else self.handle_message self.is_running = False self.thread = None def run(self, queues=None, thread=True, **kwargs): res = [] if not queues: res = [self.broker.queues[x] for x in self.broker.queues] else: if isinstance(queues, str): if queues in self.broker.queues: res = [self.broker.queues[queues]] queues = [queues] for queue in set(queues): if queue not in self.broker.queues: logger.error('no queue named {}'.format(queue)) else: res.append(self.broker.queues[queue]) if res: if thread: self.thread = Thread(target=self._run_consumer, args=(res,), kwargs=kwargs) self.thread.start() else: self._run_consumer(res, **kwargs) else: logger.warning('no queue avaible, please check again!') return None @staticmethod def handle_message(body, message): #: This is the callback applied when a message is received. print(f'Received message: {body!r}') print(f' properties:\n{pretty(message.properties)}') print(f' delivery_info:\n{pretty(message.delivery_info)}') # finally should ack this message message.ack() def _run_consumer(self, queues, **kwargs): #: Create a connection and a channel. #: If hostname, userid, password and virtual_host is not specified #: the values below are the default, but listed here so it can #: be easily changed. timeout = kwargs.get('timeout') or 1 ignore_timeouts = kwargs.get('ignore_timeouts') or True with self.broker.connection() as connection: with Consumer(connection, queues, callbacks=[self.cb], **kwargs): self.is_running = True logger.debug("mq is running at {}".format(self.broker.amqp)) while self.is_running: try: # #: Each iteration waits for a single event. Note that this # #: event may not be a message, or a message that is to be # #: delivered to the consumers channel, but any event received # #: on the connection. for _ in eventloop(connection, timeout=timeout, ignore_timeouts=ignore_timeouts): pass except ConnectionForced: self.is_running = False logger.info('MQ Received a Force Close Commend: {}'.format(e)) break except ConnectionResetError: pass except Exception as e: self.is_running = False logger.error('cb has some problem {}'.format(e), exc_info=True) break def send_as_task(self, data, block=False, **kwargs): with producers[self.broker.connection()].acquire(block=block) as producer: producer.publish(data, **kwargs) # if __name__ == '__main__': # broker = Broker() # broker.load(config_path='some_file.yaml') # mq = RabbitMQ(broker) # mq.run(thread=False) # """ demo some_file.yaml: MQCONFIG: host: 106.54.140.36 port: 5672 username: guest password: guest exchange: - name: message type: topic durable: false - name: asset.scanTaskTopic type: topic durable: true queue: - name: asset.scanTaskManage exchange: asset.scanTaskTopic routing_key: scanTaskManage durable: true - name: TEST01 exchange: message routing_key: example.text durable: false """
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/database/mq_obj.py
mq_obj.py
import pymysql from dbutils.pooled_db import PooledDB, SharedDBConnection import logging logger = logging.getLogger(__name__) class Mysql(object): """ 注意:insert,update,delete操作时需要commit """ def __init__(self, db, host, port, user, pwd): self.db = pymysql.connect(host=host, port=port, user=str(user), password=str(pwd)) self.cursor = self.db.cursor() self.current_db = db def __del__(self): self.cursor.close() self.db.close() def execute_sql(self, sql): try: self.db.ping(reconnect=True) self.db.select_db(self.current_db) # sql = sql.lower() self.cursor.execute(sql) method = sql.split()[0].lower() if method.startswith(('insert', 'update', 'delete')): self.db.commit() return True elif method.startswith('select'): return list(self.cursor.fetchall()) else: self.db.commit() logger.error('未知sql类型'.format(sql)) return False except Exception as e: logger.error('sql执行出错\nSQL: {} ,错误原因 {}'.format(sql, e), exc_info=True) return False def insert(self, tb, dt): """ :param tb: 目标插入表 :param dt: 字典型 :return: """ ls = [(k, dt[k]) for k in dt if dt[k] is not None] sql = 'insert %s (' % tb + ','.join(i[0] for i in ls) + \ ') values (' + ','.join('%r' % i[1] for i in ls) + ');' self.execute_sql(sql) def select(self, tb, *columns, **factor): """ :param tb: 目标插入表 :param columns:select内容,空为全部 :param factor: where内容 example: self.select('arm_entry_services', asset_ip='192.168.90.26') """ where = '' columns = '*' if columns == () or '' else ','.join(columns) if len(factor) > 0: where = 'where 1=1 ' for column in factor: if factor[column] == '': continue elif factor[column].startswith('like'): conditional = 'and {} {}'.format(column, factor[column]) else: conditional = 'and {}={}'.format(column, "%r" % factor[column]) if column == 'limit': where += f'{column} {factor[column]}' else: where += conditional + ' ' sql = f'select {columns} from {tb} {where}' return self.execute_sql(sql) def update(self, tb, target_dic, set_dic): ts = [(k, target_dic[k]) for k in target_dic if target_dic[k] is not None] ss = [(k, set_dic[k]) for k in set_dic if set_dic[k] is not None] sql = 'UPDATE {} SET {} WHERE {}'.format(tb, ','.join([i[0] + '=' + '%r' % i[1] for i in ss]), ' AND '.join([i[0] + '=' + '%r' % i[1] for i in ts])) self.execute_sql(sql) class MysqlPool(object): """ mysql连接池,用于处理多线程 """ def __init__(self, db, host, port, user, pwd, **kwargs): pool_config = { 'creator': pymysql, # 使用链接数据库的模块 'maxconnections': 6, # 连接池允许的最大连接数,0和None表示不限制连接数 'mincached': 2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建 'maxcached': 5, # 链接池中最多闲置的链接,0和None不限制 'maxshared': 3, # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。 'blocking': True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错 'maxusage': None, # 一个链接最多被重复使用的次数,None表示无限制 'setsession': [], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] 'ping': 1, # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always 'host': host, 'port': port, 'user': user, 'password': pwd, 'database': db, 'charset': 'utf8' } pool_config.update(**kwargs) self.pool = PooledDB(**pool_config) def __new__(cls, *args, **kw): ''' 启用单例模式 :param args: :param kw: :return: ''' if not hasattr(cls, '_instance'): cls._instance = object.__new__(cls) return cls._instance def __del__(self): try: self.pool.close() except Exception: pass def execute_sql(self, sql, **args): try: sql = sql.lower() conn, cursor = self.connect() cursor.execute(sql, args) method = sql.split()[0].lower() if method.startswith(('insert', 'update', 'delete')): conn.commit() self.connect_close(conn, cursor) return True elif method.startswith('select'): record_list = cursor.fetchall() self.connect_close(conn, cursor) return record_list else: conn.commit() # logger.error('未知sql类型'.format(sql)) return True except Exception as e: logger.error('sql执行出错\nSQL: {} ,错误原因 {}'.format(sql, e), exc_info=True) return False def connect(self): ''' 启动连接 :return: ''' conn = self.pool.connection() cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) return conn, cursor def connect_close(self, conn, cursor): ''' 关闭连接 :param conn: :param cursor: :return: ''' cursor.close() conn.close() def select_all(self, sql, args): ''' 批量查询 :param sql: :param args: :return: ''' conn, cursor = self.connect() cursor.execute(sql, args) record_list = cursor.fetchall() self.connect_close(conn, cursor) return record_list def select_one(self, sql, args): ''' 查询单条数据 :param sql: :param args: :return: ''' conn, cursor = self.connect() cursor.execute(sql, args) result = cursor.fetchone() self.connect_close(conn, cursor) return result def execute(self, sql, args): """ 执行insert/delete/update操作 :param sql: :param args: :return: """ conn, cursor = self.connect() row = cursor.execute(sql, args) conn.commit() self.connect_close(conn, cursor) return row class TaskMysql(MysqlPool, Mysql): def __init__(self, db, host, port, user, pwd, **kwargs): super().__init__(db=str(db), host=host, port=port, user=str(user), pwd=str(pwd), **kwargs)
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/database/mysql_obj.py
mysql_obj.py
from typing import Any, MutableMapping, Optional, Type, Union, Collection from elasticsearch import Elasticsearch, Transport class ES(Elasticsearch): """ 创建 index : es.indices.create(index="test", body=body) 删除 index : es.indices.delete(index='test') 插入数据: es.create(index="test", id=4, body={"name": "JOJO"}) 删除指定数据: es.delete(index='test', id=1) 修改字段: es.update(index="test", id=1, body={"doc": {"name": "张三",'sex':'男'}}) 获取数据: res = es.get(index="test", id=1) 查找所有数据: res = es.search(index='test', size=20) 根据条件查找数据: 1.匹配查询 (核心查询): body = {"query": {"match": {"name": "JOJO"}}} res = es.search(index="test", body=match) 2.词条查询,注意只能查询内容是'被分析(analyzed)'的,查询前不会再对搜索词进行分词 单匹配 body = {"query": {'term': {'id': 1}}} 多条件匹配 body = {"query": {'terms': {'id': [1,2]}}} 3.range查询: gt :: 大于 gte:: 大于等于 lt :: 小于 lte:: 小于等于 body = {"range":{"id":{"gt":2,"lt":10}}} 4.exists查询: 允许查询必须存在某个字段,且不为null body = {"query": {'exists': {'field': "sex"}}} 4.bool查询,由一个或多个类型化的bool子句构成: must:and关系,影响评分 must not:与must作用相反,且不会影响评分 filter: 不会对评分有影响 should: 如果Bool Query包含must或filter子句,则该子句主要用于评分;否则用于搜索命中文档,可以带有minimum_should_match(至少匹配几个条件)参数控制该行为 body = {"query": {"bool": {"should": [{"match": {"content": "{}".format(keywords)}}, {"match": {"title": "{}".format(keywords)}}]}}} res = es.search(index="test", body=body) 查看分词: 对于词条查询,必须查询对象是已经分词过的内容,所以需要知道目前的分词情况 res = es.termvectors(index='test', id=9, body={"fields": ['ChineseName']}) 批量操作: bulk会把将要处理的数据载入内存中,所以数据量是有限制的,最佳的数据量不是一个确定的数值,它取决于你的硬件,你的文档大小以及复杂性,你的索引以及搜索的负载。 大小建议是5-15MB,默认不能超过100M from elasticsearch.helpers import async_bulk, bulk actions = [] for i in range(3): action = {'_op_type': 'index', # 操作 index update create delete '_index': 'test', # index '_source': {'level': i}} actions.append(action) # 使用bulk方法 bulk(client=es, actions=actions) # 使用异步bulk方法 async def main(): await async_bulk(es, data) 查看所有索引:http://192.168.1.100:9210/_cat/indices?v """ def __init__(self, **kwargs: Any): self._es = super(ES, self).__init__(**kwargs) def build_host_index(self): create_body = { "settings": { "number_of_shards": 5, # 每个索引主分片数,创建后无法修改 "number_of_replicas": 2, # 每个主分片的副本数,对于索引库,这个配置可以随时修改 "blocks.read_only_allow_delete": False, # 防止磁盘使用率大导致的文件写入失败 "analysis": { "analyzer": { "ik_smart_pinyin": { "type": "custom", "tokenizer": "ik_smart", "filter": ["my_pinyin", "word_delimiter"] }, "ik_max_word_pinyin": { "type": "custom", "tokenizer": "ik_max_word", "filter": ["my_pinyin", "word_delimiter"] } }, "filter": { "my_pinyin": { "type": "pinyin", "keep_separate_first_letter": False, "keep_full_pinyin": True, "keep_original": True, "limit_first_letter_length": 16, "lowercase": True, "remove_duplicated_term": True } } } }, "mappings": { "properties": { "location": { # 地理信息 "type": "geo_point" }, "isp": { # 公司名 "type": "text", "analyzer": "ik_max_word" # 考虑到公司名可能会有中文,所以用ik分词器 }, "pro": { "type": "text", "analyzer": "ik_smart_pinyin" # "doc_values": False # 关闭不需要字段的doc values功能,仅对需要排序,汇聚功能的字段开启。 }, "city": { "type": "text", "analyzer": "ik_smart_pinyin" }, "geo": { "type": "text", "analyzer": "ik_smart_pinyin" }, "is_online": { "type": 'boolean' }, "is_ipv6": { "type": 'boolean' }, "ports_detail": { "type": "nested", # 定义嵌套类型的数据 "properties": { "port": { "type": "integer", }, "conf": { "type": "integer" }, "state": { "type": "keyword" }, "extrainfo": { "type": "text" }, "product": { "type": "text" }, "reason": { "type": "keyword" }, "version": { "type": "text" } } }, "os": { "type": 'text' }, "ip": { "type": 'ip' }, "target": { "type": 'keyword' }, "type": { "type": "keyword" }, "timestamp": { "type": "date", "format": 'yyyy-MM-dd HH:mm:ss' } } } } res = self.indices.create(index='asset', body=create_body) print(res) def build_web_index(self): create_body = { "settings": { "number_of_shards": 5, # 每个索引主分片数,创建后无法修改 "number_of_replicas": 2, # 每个主分片的副本数,对于索引库,这个配置可以随时修改 "blocks.read_only_allow_delete": False, # 防止磁盘使用率大导致的文件写入失败 "analysis": { "analyzer": { "ik_smart_pinyin": { "type": "custom", "tokenizer": "ik_smart", "filter": ["my_pinyin", "word_delimiter"] }, "ik_max_word_pinyin": { "type": "custom", "tokenizer": "ik_max_word", "filter": ["my_pinyin", "word_delimiter"] }, "domain_name_analyzer": { "filter": "lowercase", "tokenizer": "domain_name_tokenizer", "type": "custom" }, "ik_html": { "tokenizer": "ik_smart", "char_filter": ["html_strip"] } }, "tokenizer": { "domain_name_tokenizer": { "type": "PathHierarchy", "delimiter": ".", "reverse": True } }, "filter": { "my_pinyin": { "type": "pinyin", "keep_separate_first_letter": False, "keep_full_pinyin": True, "keep_original": True, "limit_first_letter_length": 16, "lowercase": True, "remove_duplicated_term": True } } } }, "mappings": { "properties": { "title": { # 网页名 "type": "text", "analyzer": "ik_max_word" # 考虑到公司名可能会有中文,所以用ik分词器 }, "status_code": { "type": "integer", }, "target": { "type": "text", "analyzer": "domain_name_analyzer" }, "domain_ip": { "type": "ip", }, "html": { "type": 'text', "analyzer": "ik_html" }, "fingerprints": { "type": "nested", # 定义嵌套类型的数据 "properties": { "name": { "type": "keyword", }, "confidence": { "type": "integer" }, "version": { "type": "text" }, "cpe": { "type": "text" }, "categories": { "type": "nested", "properties": { "id": {'type': 'keyword'}, "name": {'type': 'keyword'} } } } } } } } res = self.indices.create(index='web', body=create_body) print(res) def insert_data(self, index, body): res = self.index(index=index, body=body) return True if res['result'] == 'created' else False def test_search(self, body={}): # body = {"query": {"match": {"name": 'X11:5'}}} if not body: body = {"query": { "nested": { "path": 'ports', "query": { "match": { "ports.name": 'ssh' } } } }} res = self.search(index="asset", body=body) # return res['hits']['hits'] return res def insert_web_demo(self): body = { "title": "Adet Söktürücü Çay - Adet Ağrısı İçin Bitkisel Çay", "status_code": 200, "target": "https://51.222.183.68:443", "domain_ip": "51.222.183.68", "cert": { "source": "openssl", "MD5": "8959740FF2047EEF090B547FA195BD1F", "SHA1": "B2335FE65D2BA39F13C79B8651A75EA4D78A6319", "SHA-256": "2EBBC4395FDE53E9DEF162C3E7EB10EBD9F6C4D183AD671CB76F4D67073AC51E", "Public_Key_Modulus": "EC:E6:4E:69:75:63:10:DA:74:85:CC:52:27:C1:31:B7:C7:7A:55:44:37:B3:38:D8:E2:DA:8C:B3:FB:C1:E7:42:06:BF:A4:93:2E:2A:41:FF:59:3C:85:06:D7:96:0F:64:A8:D0:90:EF:9F:2E:9F:E5:80:1B:5E:92:13:09:DC:9E:C4:8C:AE:99:87:14:64:7B:E9:DC:E3:3D:17:D9:3B:E4:5A:AA:04:20:AA:E7:9C:5B:38:E5:3D:DE:3C:B2:DC:20:92:AB:C7:0D:BD:6D:A5:73:90:12:21:BC:8C:3E:81:48:7F:E9:5E:A7:CE:93:D8:89:02:9B:B8:13:ED:7F:36:F7:76:70:81:57:C5:4B:69:9A:B2:29:7C:16:B1:DA:71:30:FC:FB:AB:71:99:47:2B:9F:DD:46:04:CC:0A:E1:B6:39:AD:7E:AA:3D:98:07:63:12:AA:E5:13:E4:73:F8:F2:2A:FB:78:0D:60:B2:42:E3:42:AD:E5:8C:59:F5:14:E6:17:67:2E:C2:01:18:AA:4E:C6:70:88:5C:02:B4:4E:A9:9E:21:2A:75:AD:9C:AD:25:27:84:02:BB:E2:40:06:5C:E2:DC:E6:E3:BB:4B:88:B1:AB:E3:E7:F1:9B:73:60:1B:61:45:45:17:37:43:B2:5E:41:6E:18:64:07:88:10:6F:D5", "DNS_Names": [ "adetsokturucucay.com", "www.adetsokturucucay.com" ], "Names": "www.adetsokturucucay.com", "Version": "v3", "Serial_Number": "299514511984207870179040579824374379494664", "Serial_Hex": "0x37031acbdab11a68af40e29bc6bda80bd08", "Signature_Algorithm": "sha256WithRSAEncryption", "Country": "US", "Organization": "Let\"s Encrypt", "CommonName": "R3", "Not_Before": "2021-01-04 12:05:24 UTC", "Not_After": "2021-04-04 12:05:24 UTC", "Is_Expired": False, "Public_Key_Bits": 2048, "Public_Key": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7OZOaXVjENp0hcxSJ8Ex\nt8d6VUQ3szjY4tqMs/vB50IGv6STLipB/1k8hQbXlg9kqNCQ758un+WAG16SEwnc\nnsSMrpmHFGR76dzjPRfZO+RaqgQgquecWzjlPd48stwgkqvHDb1tpXOQEiG8jD6B\nSH/pXqfOk9iJApu4E+1/Nvd2cIFXxUtpmrIpfBax2nEw/PurcZlHK5/dRgTMCuG2\nOa1+qj2YB2MSquUT5HP48ir7eA1gskLjQq3ljFn1FOYXZy7CARiqTsZwiFwCtE6p\nniEqda2crSUnhAK74kAGXOLc5uO7S4ixq+Pn8ZtzYBthRUUXN0OyXkFuGGQHiBBv\n1QIDAQAB\n-----END PUBLIC KEY-----\n", "CA": True, "is_effective": False }, "html": "", "headers": { "Connection": "keep-alive", "Content-Type": "text/html; charset=UTF-8", "X-Redirect-By": "WordPress", "Location": "https://adetsokturucucay.com/", "X-LiteSpeed-Cache": "hit", "Content-Length": "0", "Date": "Fri, 12 Mar 2021 07:05:56 GMT", "Server": "cloudflare", "Alt-Svc": "h3-27=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-29=\":443\"; ma=86400", "Transfer-Encoding": "chunked", "Set-Cookie": "__cfduid=dea74bbe5f7da7f16547e544f53bf92241615532755; expires=Sun, 11-Apr-21 07:05:55 GMT; path=/; domain=.adetsokturucucay.com; HttpOnly; SameSite=Lax", "Link": "<https://adetsokturucucay.com/wp-json/>; rel=\"https://api.w.org/\", <https://adetsokturucucay.com/>; rel=shortlink", "Vary": "Accept-Encoding", "X-Turbo-Charged-By": "LiteSpeed", "CF-Cache-Status": "DYNAMIC", "cf-request-id": "08c6daa39d000042ea093e0000000001", "Expect-CT": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", "Report-To": "{\"group\":\"cf-nel\",\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report?s=2F%2FVLB0gSe9Ldf1yGlMn4CGaO5S14%2F4KLCHzGdBZ8TpUccJmNb6lCOJcQ9joLW3dtPYFOQTqGJkCNpChGfGXgPNaUvxrYkVctaPzDKtbPkr7WCWIyw%3D%3D\"}],\"max_age\":604800}", "NEL": "{\"max_age\":604800,\"report_to\":\"cf-nel\"}", "CF-RAY": "62eb2d4c2ced42ea-LAX", "Content-Encoding": "gzip" }, "fingerprints": [ { "slug": "wordpress", "name": "WordPress", "confidence": 100, "version": "5.2.9", "cpe": "cpe:/a:wordpress:wordpress", "categories": [ { "id": 1, "slug": "cms", "name": "CMS" }, { "id": 11, "slug": "blogs", "name": "Blogs" } ] }, { "slug": "mysql", "name": "MySQL", "confidence": 100, "version": None, "cpe": "cpe:/a:mysql:mysql", "categories": [ { "id": 34, "slug": "databases", "name": "Databases" } ] }, { "slug": "php", "name": "PHP", "confidence": 100, "version": None, "cpe": "cpe:/a:php:php", "categories": [ { "id": 27, "slug": "programming-languages", "name": "Programming languages" } ] }, { "slug": "litespeed-cache", "name": "Litespeed Cache", "confidence": 100, "version": None, "cpe": None, "categories": [ { "id": 23, "slug": "caching", "name": "Caching" } ] }, { "slug": "all-in-one-seo-pack", "name": "All in One SEO Pack", "confidence": 100, "version": "3.1.1", "cpe": "cpe:/a:semperfiwebdesign:all_in_one_seo_pack", "categories": [ { "id": 54, "slug": "seo", "name": "SEO" } ] }, { "slug": "google-font-api", "name": "Google Font API", "confidence": 100, "version": None, "cpe": None, "categories": [ { "id": 17, "slug": "font-scripts", "name": "Font scripts" } ] }, { "slug": "font-awesome", "name": "Font Awesome", "confidence": 100, "version": None, "cpe": None, "categories": [ { "id": 17, "slug": "font-scripts", "name": "Font scripts" } ] }, { "slug": "jquery-migrate", "name": "jQuery Migrate", "confidence": 100, "version": "1.4.1", "cpe": None, "categories": [ { "id": 59, "slug": "javascript-libraries", "name": "JavaScript libraries" } ] }, { "slug": "jquery", "name": "jQuery", "confidence": 100, "version": "1.12.4", "cpe": "cpe:/a:jquery:jquery", "categories": [ { "id": 59, "slug": "javascript-libraries", "name": "JavaScript libraries" } ] }, { "slug": "google-analytics", "name": "Google Analytics", "confidence": 100, "version": None, "cpe": None, "categories": [ { "id": 10, "slug": "analytics", "name": "Analytics" }, { "id": 61, "slug": "saas", "name": "SaaS" } ] }, { "slug": "cloudflare", "name": "Cloudflare", "confidence": 100, "version": None, "cpe": None, "categories": [ { "id": 31, "slug": "cdn", "name": "CDN" } ] } ] } res = self.index(index='web', body=body) return True if res['result'] == 'created' else False def delete_all(self): self.delete_by_query(index='asset', body={"query": {"match_all": {}}}, timeout=100) if __name__ == '__main__': es = ES(host="localhost", port=9200) es.build_web_index() # es.insert_web_demo() es.build_host_index() # print(es.test_search()) # es.delete(index='asset',id='3N_57HcBjFzHMmQJCEhN') # es.delete_all() # body = { # 更新表结构,但是我不知道怎么用python去进行更新 # "properties": { # "ChineseName": { # "type": "text", # "analyzer": "ik_max_word" # }}} # res = es.termvectors(index='test', id=11, body={"fields": ['ChineseName']}) # print(res) # # 滚动分页的func,第四块部分 分页查询中 说明 # es.scroll(scroll_id="scroll_id", scroll="5m")
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/database/es_obj.py
es_obj.py
import pymongo from pymongo import MongoClient import re """ use admin db.createUser( { user: "XXX", pwd: "XXXXXXX", roles: [ { role: "root", db: "admin" } ] } ) 再开启验证(mongod.conf) 删除用户: use XXXX db.dropUser('XXXXX') 修改多个文档的某一个字段: db.XXX.update({"DDD":{"$exists":true}},{$set:{"DDD":W}},{multi:true}) """ class BaseMongoDB(object): """ 数据库基类 """ asc = pymongo.ASCENDING desc = pymongo.DESCENDING def __init__(self, name, host, port, db, **kwargs): self.name = name # self.client = MongoClient(host, port, **kwargs) # self.client.admin.authenticate(config.database.username, config.database.password) if 'password' in kwargs and 'user' in kwargs and 'source' in kwargs: mongo_url = 'mongodb://{0}:{1}@{2}:{3}/?authSource={4}&authMechanism=SCRAM-SHA-1'.format( kwargs['user'], kwargs['password'], host, port, kwargs['source']) else: mongo_url = 'mongodb://{0}:{1}'.format(host, port) # mongo_url = parse.quote(mongo_url) self.client = MongoClient(mongo_url) self.db = self.client[db] self.task = self.db[self.name] def change_table(self, name): self.name = name self.task = self.db[self.name] def get_one(self, key: dict, **kwargs): return self.task.find_one(key, **kwargs) def find(self, key: dict, **kwargs): return self.task.find(key, **kwargs) def get_all(self): return [data for data in self.task.get()] def delete_many(self, key: dict): return self.task.delete_many(key).deleted_count def delete_one(self, key: dict): return self.task.delete_one(key).raw_result def put(self, obj: dict): return self.task.insert_one(obj) def update_many(self, key: dict, obj: dict): return self.task.update_many(key, {"$set": obj}, upsert=True).raw_result def update_one(self, key: dict, obj: dict): return self.task.update_one(key, {"$set": obj}, upsert=True).raw_result def push_one(self, key: dict, where: str, obj: dict): """ 向array插入一条数据 e.g. mongodb_cursor.push_one({'id': 0}, 'standby', {'task_id': 'mongopushtest', 'number': 'heyhey'}) """ return self.task.update_one(key, {"$push": {where: obj}}, upsert=True).raw_result def pull_one(self, key: dict, obj: dict): """ 从array删除一条数据 e.g. mongodb_cursor.pull_one({'id': 0}, {'standby': {'task_id': 'mongopushtest'}}) """ return self.task.update_one(key, {"$pull": obj}, upsert=True).raw_result def pull_many(self, key: dict, where, obj: dict, result=True): """从array删除满足条件的所有数据,并返回内容""" def issubset(a: dict, b: dict): return set(a.items()).issubset(b.items()) if result: res = [] raw = self.task.find_and_modify(key, {"$pull": {where: obj}}, upsert=True) for item in obj: if '$regex' in obj[item]: # 处理正则搜索情况 key = item word = obj[item]['$regex'][1:] for i in raw[where]: if str(i[key]).startswith(word): res.append(i) return res for item in raw[where]: if issubset(obj, item): res.append(item) return res else: return self.task.find(key, {"$pull": {where: obj}}, upsert=True) def pop_one(self, key: dict, where: str) -> dict: """ 从array弹出最早的一条数据 注意目前where只支持一级目录,不支持比较复杂位置的array(后期再优化吧 """ res = self.task.find_one_and_update(key, {"$pop": {where: -1}}, upsert=True) return res[where][0] if res[where] else {} def increment_one(self, key: dict, obj_key: str, step: int): """ 对表里的某个数进行自增、自减操作 [注意]对于嵌套型的数据,需要使用如下格式 obj_key: "scan_type.s" :param key: 索引的key :param obj_key:目标的key :param step: 增减幅度 :return: """ return self.task.update_one(key, {"$inc": {obj_key: step}}) @staticmethod def sql_condition(sql): condition = {} modifier = {'<=': '$lte', '>=': '$gte', '=': '$eq', '>': '$gt', '<': '$lt', 'like': '$regex'} split_symbol = f"\s({'|'.join([i for i in modifier.keys()])})\s" # 先对and处理 sql = sql.split(' and ') sql = [re.split(split_symbol, i.strip(), maxsplit=1) for i in sql] for s in sql: s = [i.strip() for i in s] s[2] = int(s[2]) if re.sub('\d+', '', s[2]) == '' else s[2] if s[1] == 'like': if s[2].startswith('%') and s[2].endswith('%'): s[2] = s[2].strip('%') condition[s[0]] = {modifier[s[1]]: s[2]} return condition """ 由于mongodb中key值不能存在'.',故对于字典的key值全部进行转换 于是有下面的两个方法 """ def save_change(d, m='|'): """ 清洗变量d,将其中所有字典key的'.'变为'|'(或自定义m) """ if not isinstance(d, dict): pass else: _point_to_m(d, m) for key in list(d): save_change(d[key]) return d def load_change(d, m='|'): """ 清洗变量d,将其中所有字典key的'|'(或自定义m)变为'.' """ if not isinstance(d, dict): pass else: _m_to_point(d, m) for key in list(d): load_change(d[key]) return d def _point_to_m(t: dict, m='|'): for key in list(t): if '.' in key: nk = str(key).replace('.', m) t[nk] = t.pop(key) return t def _m_to_point(t: dict, m='|'): for key in list(t): if '.' in key: nk = str(key).replace(m, '.') t[nk] = t.pop(key) return t
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/database/mongodb_obj.py
mongodb_obj.py
import functools import logging import time import pika from pika.adapters.asyncio_connection import AsyncioConnection from pika.exchange_type import ExchangeType logger = logging.getLogger(__name__) logger.name = 'RabbitMQ' class AsyncConsumer(object): """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, this class will stop and indicate that reconnection is necessary. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, amqp_url, queue, routing_key, exchange, exchange_type=ExchangeType.topic, loop=None, durable=True, callback=None): """Create a new instance of the consumer class, passing in the AMQP URL used to connect to RabbitMQ. :param str amqp_url: The AMQP url to connect with :param str queue: 消息队列名称 :param str routing_key: routing_key :param str exchange: exchanges名 :param str exchange_type: exchanges类型 - 'direct' 'fanout' 'headers' 'topic' :param asyncio.new_event_loop loop: 在子线程中需要实例化一个新的event_loop :param bool durable: 持久 :param func callback: 接收到数据后的callback函数,传参是basic_deliver, properties, body """ self.should_reconnect = False self.was_consuming = False self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = amqp_url self._consuming = False # In production, experiment with higher prefetch values # for higher consumer throughput self._prefetch_count = 1 self.EXCHANGE = exchange self.EXCHANGE_TYPE = exchange_type self.QUEUE = queue self.ROUTING_KEY = routing_key self.custom_ioloop = loop self.durable = durable self.callback = callback def connect(self): """This method connects to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.adapters.asyncio_connection.AsyncioConnection """ logger.info('Connecting to %s', self._url) return AsyncioConnection( parameters=pika.URLParameters(self._url), on_open_callback=self.on_connection_open, on_open_error_callback=self.on_connection_open_error, on_close_callback=self.on_connection_closed, custom_ioloop=self.custom_ioloop) def close_connection(self): self._consuming = False if self._connection.is_closing or self._connection.is_closed: logger.info('Connection is closing or already closed') else: logger.info('Closing connection') self._connection.close() def on_connection_open(self, _unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :param pika.adapters.asyncio_connection.AsyncioConnection _unused_connection: The connection """ logger.info('Connection opened') self.open_channel() def on_connection_open_error(self, _unused_connection, err): """This method is called by pika if the connection to RabbitMQ can't be established. :param pika.adapters.asyncio_connection.AsyncioConnection _unused_connection: The connection :param Exception err: The error """ logger.error('Connection open failed: %s', err) self.reconnect() def on_connection_closed(self, _unused_connection, reason): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param Exception reason: exception representing reason for loss of connection. """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reconnect necessary: %s', reason) self.reconnect() def reconnect(self): """Will be invoked if the connection can't be opened or is closed. Indicates that a reconnect is necessary then stops the ioloop. """ self.should_reconnect = True self.stop() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened') self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self.EXCHANGE) def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reason): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param Exception reason: why the channel was closed """ logger.warning('Channel %i was closed: %s', channel, reason) self.close_connection() def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange: %s', exchange_name) # Note: using functools.partial is not required, it is demonstrating # how arbitrary data can be passed to the callback when it is called cb = functools.partial( self.on_exchange_declareok, userdata=exchange_name) self._channel.exchange_declare( exchange=exchange_name, exchange_type=self.EXCHANGE_TYPE, callback=cb, durable=self.durable) def on_exchange_declareok(self, _unused_frame, userdata): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame :param str|unicode userdata: Extra user data (exchange name) """ logger.info('Exchange declared: %s', userdata) self.setup_queue(self.QUEUE) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue %s', queue_name) cb = functools.partial(self.on_queue_declareok, userdata=queue_name) self._channel.queue_declare(queue=queue_name, callback=cb, durable=self.durable) def on_queue_declareok(self, _unused_frame, userdata): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method _unused_frame: The Queue.DeclareOk frame :param str|unicode userdata: Extra user data (queue name) """ queue_name = userdata logger.info('Binding %s to %s with %s', self.EXCHANGE, queue_name, self.ROUTING_KEY) cb = functools.partial(self.on_bindok, userdata=queue_name) self._channel.queue_bind( queue_name, self.EXCHANGE, routing_key=self.ROUTING_KEY, callback=cb) def on_bindok(self, _unused_frame, userdata): """Invoked by pika when the Queue.Bind method has completed. At this point we will set the prefetch count for the channel. :param pika.frame.Method _unused_frame: The Queue.BindOk response frame :param str|unicode userdata: Extra user data (queue name) """ logger.info('Queue bound: %s', userdata) self.set_qos() def set_qos(self): """This method sets up the consumer prefetch to only be delivered one message at a time. The consumer must acknowledge this message before RabbitMQ will deliver another one. You should experiment with different prefetch values to achieve desired performance. """ self._channel.basic_qos( prefetch_count=self._prefetch_count, callback=self.on_basic_qos_ok) def on_basic_qos_ok(self, _unused_frame): """Invoked by pika when the Basic.QoS method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method _unused_frame: The Basic.QosOk response frame """ logger.info('QOS set to: %d', self._prefetch_count) self.start_consuming() def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._consumer_tag = self._channel.basic_consume( self.QUEUE, self.on_message) self.was_consuming = True self._consuming = True def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ logger.info('Consumer was cancelled remotely, shutting down: %r', method_frame) if self._channel: self._channel.close() def on_message(self, _unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel _unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param bytes body: The message body """ logger.info('Received message # %s from %s: %s', basic_deliver.delivery_tag, properties.app_id, body) if self.callback: try: self.callback(basic_deliver, properties, body) except Exception: pass self.acknowledge_message(basic_deliver.delivery_tag) def acknowledge_message(self, delivery_tag): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message %s', delivery_tag) self._channel.basic_ack(delivery_tag) def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') cb = functools.partial( self.on_cancelok, userdata=self._consumer_tag) self._channel.basic_cancel(self._consumer_tag, cb) def on_cancelok(self, _unused_frame, userdata): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method _unused_frame: The Basic.CancelOk frame :param str|unicode userdata: Extra user data (consumer tag) """ self._consuming = False logger.info( 'RabbitMQ acknowledged the cancellation of the consumer: %s', userdata) self.close_channel() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the AsyncioConnection to operate. """ self._connection = self.connect() self._connection.ioloop.run_forever() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ if not self._closing: self._closing = True logger.info('Stopping') if self._consuming: self.stop_consuming() self._connection.ioloop.run_forever() else: self._connection.ioloop.stop() logger.info('Stopped') class ReconnectingAsyncConsumer(object): """This is an example consumer that will reconnect if the nested ExampleConsumer indicates that a reconnect is necessary. """ def __init__(self, amqp_url, **kwargs): self._reconnect_delay = 0 self._amqp_url = amqp_url self.config = kwargs self._consumer = AsyncConsumer(self._amqp_url, **self.config) def run(self): while True: try: self._consumer.run() except KeyboardInterrupt: self._consumer.stop() break self._maybe_reconnect() def _maybe_reconnect(self): if self._consumer.should_reconnect: self._consumer.stop() reconnect_delay = self._get_reconnect_delay() logger.info('Reconnecting after %d seconds', reconnect_delay) time.sleep(reconnect_delay) self._consumer = AsyncConsumer(self._amqp_url, **self.config) def _get_reconnect_delay(self): if self._consumer.was_consuming: self._reconnect_delay = 0 else: self._reconnect_delay += 1 if self._reconnect_delay > 30: self._reconnect_delay = 30 return self._reconnect_delay class Publisher: def __init__(self, host, port='5672', credential=False, username=None, password=None, erase_on_connect=False, **kwargs): self.configs = { 'host': host, 'port': port } if credential and username and password: self.credentials = pika.credentials.PlainCredentials(username, password, erase_on_connect) self.configs['credentials'] = self.credentials self.configs.update(**kwargs) self._connection = pika.BlockingConnection(pika.ConnectionParameters(**self.configs)) self._channel = self._connection.channel() # open_channel self._closed = False def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if not self._closed: self.close() def close(self): self._connection.close() self._closed = True def publish(self, exchange, routing_key, body): logger.info('Publishing message # %s to %s/%s', body, exchange, routing_key) self._channel.basic_publish( exchange=exchange, routing_key=routing_key, body=body # pika.BasicProperties(content_type='text/plain',delivery_mode=DeliveryMode.Transient) ) logger.info('Sent message # %s') def setup_exchange(self, exchange_name, exchange_type, **kwargs): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ # Note: using functools.partial is not required, it is demonstrating # how arbitrary data can be passed to the callback when it is called # cb = functools.partial( # self.on_exchange_declareok, userdata=exchange_name) self._channel.exchange_declare( exchange=exchange_name, exchange_type=exchange_type, # callback=cb, **kwargs)
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/database/rabbitmq_obj.py
rabbitmq_obj.py
from kafka.admin import KafkaAdminClient, NewTopic from kafka import KafkaConsumer, KafkaProducer from kafka.errors import kafka_errors import traceback import json import datetime import calendar def default(obj): if isinstance(obj, datetime.datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() return calendar.timegm(obj.timetuple()) + obj.microsecond / 1000000.0 raise TypeError("%r is not JSON serializable" % obj) class BaseKafka: def __init__(self, bootstrap_servers): """ :param bootstrap_servers: 'host[:port]' string (or list of 'host[:port]' strings) that the consumer should contact to bootstrap initialcluster metadata. This does not have to be the full node list.It just needs to have at least one broker that will respond to a Metadata API Request. Default port is 9092. If no servers are specified, will default to localhost:9092. """ self.bootstrap_servers = bootstrap_servers self.consumers = {} self.producers = {} self.group = {} self.started_consumers = [] self.stopped_consumers = [] def create_topics(self, topics: list): """ :param topics: :return: """ client = KafkaAdminClient(bootstrap_servers=self.bootstrap_servers) client.create_topics(new_topics=topics) @staticmethod def get_new_topic(name, num_partitions, **configs): return NewTopic(name=name, num_partitions=num_partitions, **configs) def create_consumer(self, topic, **kwargs): c = KafkaConsumer( topic, # 指定消费者的消费的topic bootstrap_servers=self.bootstrap_servers, # group_id='group1', # 确定消费者的group,一旦已经有一个有group的消费者消费,同group的消费者不会再消费这条数据 如果更改了group,则会从最新的offset开始消费 # key_deserializer=lambda v: v.decode(), value_deserializer=lambda v: json.loads(v), **kwargs) self.consumers[c.config['client_id']] = c return c def create_producer(self): p = KafkaProducer( bootstrap_servers=self.bootstrap_servers, # key_serializer=str.encode, value_serializer=lambda v: json.dumps(v).encode('utf-8')) # Serialize json messages self.producers[p.config['client_id']] = p return p # def create_producer(self, indent): # p = KafkaProducer( # bootstrap_servers=self.bootstrap_servers, # key_serializer=str.encode, # value_serializer=lambda v: json.dumps(v, default=default, sort_keys=False, # indent=indent, encoding="utf-8")) # # Serialize json messages # self.producers[p.config['client_id']] = p # return p @staticmethod def use_consumer(consumer): for message in consumer: # TODO print("receive, key: {}, value: {}".format(message.key, message.value)) @staticmethod def use_producer(producer, topic, dic): future = producer.send( topic, key='count_num', # 同一个key值,会被送至同一个分区,可以不指定 value=dic) # print("sending {}".format(dic)) try: res = future.get(timeout=10) # 监控是否发送成功 return res except kafka_errors: # 发送失败抛出kafka_errors traceback.format_exc() def get_one_producer(self, client_id=None): if client_id and client_id in self.producers: return self.producers[client_id] elif len(self.producers) != 0: return self.producers[list(self.producers)[0]] else: return self.create_producer()
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/database/kafka_obj.py
kafka_obj.py
import requests import logging from requests.models import Response logger = logging.getLogger(__name__) class BaseMSG: @classmethod def msg(cls, res, **kwargs): """ 新修改判断逻辑,对于已有字段若更新为None则不更新 :keyword enforce_update: bool 是否强制更新 e.g. MSG.Success(code=None) <<< {'code': 0, 'msg': '成功'} MSG.Success(code=None,enforce_update=True) <<< {'code': None, 'msg': '成功'} """ # 修改写法,不接受更新参数为None的值 if 'enforce_update' in kwargs and kwargs['enforce_update']: kwargs.pop('enforce_update') res.update(kwargs) else: res.update((k, v) for k, v in kwargs.items() if (k not in res) or v) return res # def change_user_agent(): # from fake_useragent import UserAgent # ua = UserAgent() # session.headers['User-Agent'] = ua.random # session.headers['X-forwarded-for'] = '49.49.49.49' def safe_requests(url, method, session=None, **kwargs): # change_user_agent() try: if session: res = session.request(url=url, method=method, **kwargs) else: res = requests.request(url=url, method=method, **kwargs) return res except Exception as e: if 'Failed to establish a new connection:' in str(e): logger.warning(e) else: logger.warning(e, exc_info=True) return str(e) def _check_whos_guo(url, res): """去识别谁的锅""" if isinstance(res, str): if 'Failed to establish a new connection:' in res: logger.warning('无法访问url: {}'.format(url)) else: logger.warning('访问 {} 发生意外错误 {}'.format(url, res)) else: logger.warning("访问 {} 返回状态码 {}\n文本内容为 {}".format(res.url, res.status_code, res.text)) def get_html(url, session=None): res = safe_requests(url, session=session, method='GET') if isinstance(res, Response): if res.status_code == 200: return res.text return False def get_cookie(url, session=None): res = safe_requests(url, session=None, method='GET') return res.cookies def post_data(url, data, session=None, encode='utf-8', check_whos_guo=False): """以字符串形式发送数据""" res = safe_requests(url, session=session, method='POST', data=str(data).encode(encode)) if isinstance(res, Response): if res.status_code == 200: return res if check_whos_guo: _check_whos_guo(url, res) return False def post_json_data(url, data, session=None, check_whos_guo=False): """以json形式发送数据""" if isinstance(data, dict): pass else: if not isinstance(data, list): data = [data] data = dict(enumerate(data)) res = safe_requests(url, session=session, method='POST', json=data) if isinstance(res, Response): if res.status_code == 200: return res if check_whos_guo: _check_whos_guo(url, res) return False def post_body_json_data(url, data, session=None, check_whos_guo=False): """以json形式发送数据,数据会放在body中,这是漏扫后台可以接收的数据格式""" import json res = safe_requests(url, session=session, method='POST', data=json.dumps(data, ensure_ascii=False).encode('utf-8'), headers={'Content-Type': 'application/json'}) if isinstance(res, Response): if res.status_code == 200: return res if check_whos_guo: _check_whos_guo(url, res) return False def get(url, session=None, **kwargs): return safe_requests(url, session=session, method='GET', **kwargs) def post(url, session=None, **kwargs): return safe_requests(url, session=session, method='POST', **kwargs) def get_title(body): """ 根据页面源码返回标题 :param body: <title>sss</title> :return: sss """ import re result = '' title_patten = re.compile(rb'<title>([^<]{1,200})</title>', re.I) title = title_patten.findall(body) if len(title) > 0: try: result = title[0].decode("utf-8") except Exception as e: result = title[0].decode("gbk", errors="replace") return result.strip() def get_headers(conn: requests.Response): # version 字段目前只能是10或者11 raw = conn.raw version = "1.1" if raw.version == 10: version = "1.0" first_line = "HTTP/{} {} {}\n".format(version, raw.status, raw.reason) headers = str(raw._fp.headers) headers = headers.strip() if not conn.headers.get("Content-Length"): headers = "{}\nContent-Length: {}".format(headers, len(conn.content)) return first_line + headers
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/network/html.py
html.py
import time import base64 import hmac import urllib.parse import hashlib import logging import smtplib, ssl from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from .html import safe_requests class Config: # 待完善 DINGDING_SECRET = "" DINGDING_ACCESS_TOKEN = "" EMAIL_HOST = "" EMAIL_PORT = "" EMAIL_USERNAME = "" EMAIL_PASSWORD = "" EMAIL_TO = "" logger = logging.getLogger(__name__) class Push(object): """docstring for ClassName""" def __init__(self, asset_map, asset_counter): super(Push, self).__init__() self.asset_map = asset_map self.asset_counter = asset_counter self._domain_info_list = None self._site_info_list = None self.domain_len = self.asset_counter.get("domain", 0) self.site_len = self.asset_counter.get("site", 0) self.task_name = self.asset_map.get("task_name", "") @property def domain_info_list(self): if self._domain_info_list is None: self._domain_info_list = self.build_domain_info_list() return self._domain_info_list @property def site_info_list(self): if self._site_info_list is None: self._site_info_list = self.build_site_info_list() return self._site_info_list def build_domain_info_list(self): if "domain" not in self.asset_map: return [] domain_info_list = [] for old in self.asset_map["domain"]: domain_dict = dict() domain_dict["域名"] = old["domain"] domain_dict["解析类型"] = old["type"] domain_dict["记录值"] = old["record"][0] domain_info_list.append(domain_dict) return domain_info_list def build_site_info_list(self): if "site" not in self.asset_map: return [] site_info_list = [] for old in self.asset_map["site"]: site_dict = dict() site_dict["站点"] = old["site"] site_dict["标题"] = old["title"] site_dict["状态码"] = old["status"] site_dict["favicon"] = old["favicon"].get("hash", "") site_info_list.append(site_dict) return site_info_list def _push_dingding(self): tpl = "[{}]新发现域名 `{}` , 站点 `{}`\n***\n".format(self.task_name, self.domain_len, self.site_len) tpl = "{}\n{}".format(tpl, dict2dingding_mark(self.domain_info_list)) tpl += "\n***\n" tpl = "{}\n{}".format(tpl, dict2dingding_mark(self.site_info_list)) ding_out = dingding_send(msg=tpl, access_token=Config.DINGDING_ACCESS_TOKEN, secret=Config.DINGDING_SECRET, msgtype="markdown") if ding_out["errcode"] != 0: logger.warning("发送失败 \n{}\n {}".format(tpl, ding_out)) return False return True def _push_email(self): tpl = "<div> 新发现域名 {}, 站点 {}\n</div>".format(self.domain_len, self.site_len) html = tpl html += "<br/>" html += dict2table(self.domain_info_list) html += "<br/><br/>" html += dict2table(self.site_info_list) title = "[{}] 灯塔消息推送".format(self.task_name) send_email(host=Config.EMAIL_HOST, port=Config.EMAIL_PORT, mail=Config.EMAIL_USERNAME, password=Config.EMAIL_PASSWORD, to=Config.EMAIL_TO, title=title, html=html) return True def push_dingding(self): try: if Config.DINGDING_ACCESS_TOKEN and Config.DINGDING_SECRET: if self._push_dingding(): logger.info("push dingding succ") return True except Exception as e: logger.warning(self.task_name, e) def push_email(self): try: if Config.EMAIL_HOST and Config.EMAIL_USERNAME and Config.EMAIL_PASSWORD: self._push_email() logger.info("send email succ") return True except Exception as e: logger.warning(self.task_name, e) def message_push(asset_map, asset_counter): logger.info("ARL push run") p = Push(asset_map=asset_map, asset_counter=asset_counter) p.push_dingding() p.push_email() def dict2dingding_mark(info_list): if not info_list: return "" title_tpl = ' \t\t '.join(map(str, info_list[0].keys())) items_tpl = "" cnt = 0 for row in info_list: cnt += 1 row = ' \t '.join(map(str, row.values())) items_tpl += "{}. {}\n".format(cnt, row) return "{}\n{}".format(title_tpl, items_tpl) def dingding_send(msg, access_token, secret, msgtype="text", title="灯塔消息推送"): ding_url = "https://oapi.dingtalk.com/robot/send?access_token={}".format(access_token) timestamp = str(round(time.time() * 1000)) secret_enc = secret.encode('utf-8') string_to_sign = '{}\n{}'.format(timestamp, secret) string_to_sign_enc = string_to_sign.encode('utf-8') hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() sign = urllib.parse.quote_plus(base64.b64encode(hmac_code)) param = "&timestamp={}&sign={}".format(timestamp, sign) ding_url = ding_url + param send_json = { "msgtype": msgtype, "text": { "content": msg }, "markdown": { "title": title, "text": msg } } conn = safe_requests(ding_url, method='post', json=send_json) return conn.json() def send_email(host, port, mail, password, to, title, html, smtp_timeout=10): context = ssl.create_default_context() if port == 465: server = smtplib.SMTP_SSL(host, port, context=context, timeout=smtp_timeout) else: server = smtplib.SMTP(host, port, timeout=smtp_timeout) msg = MIMEMultipart() msg['Subject'] = title msg['From'] = mail msg['To'] = to part1 = MIMEText(html, "html", "utf-8") msg.attach(part1) server.login(mail, password) server.send_message(msg) server.close() def dict2table(info_list): if not info_list: return "" html = "" table_style = 'style="border-collapse: collapse;"' table_start = '<table {}>\n'.format(table_style) table_end = '</table>\n' style = 'style="border: 0.5pt solid windowtext;"' thead_start = '<thead><tr><th {}>序号</th><th {}>\n'.format(style, style) thead_end = '\n</th></tr></thead>' th_join_tpl = '</th>\n<th {}>'.format(style) thead_tpl = th_join_tpl.join(map(str, info_list[0].keys())) html += table_start html += thead_start html += thead_tpl html += thead_end tbody = "<tbody>\n" cnt = 0 for row in info_list: cnt += 1 td_join_tpl = '</td>\n<td {}>'.format(style) row_start = '<tr><td {}>{}</td>\n<td {}>'.format(style, cnt, style) items = [str(x).replace('>', "&#x3e;").replace('<', "&#x3c;") for x in row.values()] row = td_join_tpl.join(items) row_end = '</td>\n</tr>' row_tpl = row_start + row + row_end tbody = tbody + row_tpl + "\n" html = html + tbody + "</tbody>" + table_end return html
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/network/push.py
push.py
import re import json import logging from IPy import IP, IPSet from tld import get_tld from .html import get_html, post_data logger = logging.getLogger(__name__) INTERNAL_IP_LIST = ['10.0.0.0/8', '127.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10'] MASK = [128, 192, 224, 240, 248, 252, 254, 255] def get_addr_from_ip_by_whois(ip): try: api = f'http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true' info = get_html(api) info = json.loads(info) info = json.loads(info) res = info except Exception as e: logger.warning(e, exc_info=True) res = False return res def get_jw_from_addr_by_mapqq(city): try: api = 'https://apis.map.qq.com/jsapi?qt=poi&wd=' + city info = get_html(api) info = json.loads(info) pointx = info['detail']['city']['pointx'] pointy = info['detail']['city']['pointy'] except Exception as e: logger.warning(e, exc_info=True) pointx = 0 pointy = 0 return pointx, pointy def get_fingerprint_from_ip_by_whatweb(target): api = 'http://whatweb.bugscaner.com/what.go' _data = {'url': target, 'location_capcha': 'no'} try: info = post_data(api, _data) print('获取信息', info) if info: res = info else: res = False except Exception as e: logger.warning(e) res = False return json.loads(res.text) def is_domain(domain, use_tld=False): """判断是否是域名,use_tld会判断的更加精准一些,但是会耗费时间(大概20倍)""" res = True if '.' not in domain: return False if not use_tld: if re.match('(.+?\.)+[a-zA-Z0-9]+', domain): pass else: return False else: try: res = get_tld(domain) except Exception as e: if "didn't match any existing TLD name" in str(e): try: if domain.startswith('http') and re.search( r'((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}', domain): return True except: pass return False return res def is_ip(target): """判断是否是ip""" try: res = IP(target) return res if res and res.len() == 1 else False except ValueError: return False def is_ipv6(target): """判断是否是IPv6""" try: tmp = is_ip(target) return tmp and tmp.version() == 6 except Exception: return False def is_ipv4(target): """判断是否是IPv4""" try: tmp = is_ip(target) return tmp and tmp.version() == 4 except Exception: return False def is_ipv4_cidr(target): """判断是否是IPv4的网段""" return re.search( r'^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}\/(([12]{0,1}[0-9])|(3[0-2]))$', target) # ########################分割IP段部分######################### def split(ip_str: str): try: if is_ipv4_cidr(ip_str): ip, mask = ip_str.split('/') tmp = IP(ip).make_net(mask) ip_str = str(tmp) return split_cidr(ip_str) except: if len(ip_str.split('.')) == 4: return split_star_and_sections(ip_str) elif len(ip_str.split('.')) == 7 and '-' in ip_str: return split_ip_s_ip(ip_str) else: raise ValueError('{} is a invalid ip like str'.format(ip_str)) def split_star_and_sections(ip: str): """ 处理各处带星号、带横杠的单ip :param ip: 192.168.1.* 192.168.1-5.* """ ips = list(ip.split('.')) for index, num in enumerate(ips): if '-' in num: try: start, end = num.split('-') assert start.isdigit(), end.isdigit() ips[index] = [x for x in range(int(start), int(end) + 1)] except (ValueError, AssertionError): ips[index] = [x for x in range(1, 256)] elif num.isdigit(): ips[index] = [num] else: ips[index] = [x for x in range(1, 256)] return ['{}.{}.{}.{}'.format(n0, n1, n2, n3) for n3 in ips[3] for n2 in ips[2] for n1 in ips[1] for n0 in ips[0]] def split_ip_s_ip(ip2ip_str): """ 处理两个具体ip的范围 :param ip2ip_str: 形如192.168.1.250-192.168.2.5 """ ipx = ip2ip_str.split('-') ip2num = lambda x: sum([256 ** i * int(j) for i, j in enumerate(x.split('.')[::-1])]) num2ip = lambda x: '.'.join([str(x // (256 ** i) % 256) for i in range(3, -1, -1)]) a = [num2ip(i) for i in range(ip2num(ipx[0]), ip2num(ipx[1]) + 1) if not ((i + 1) % 256 == 0 or i % 256 == 0)] return a def split_cidr(ip): """ 处理标准ip段 :param ip: 192.168.1.0/24 """ return [str(i) for i in IP(ip)] def get_ip_set(ip_list: list) -> IPSet: ip_set = IPSet() for ip in ip_list: if is_ipv4_cidr(ip): ip, mask = ip.split('/') ip = str(IP(ip).make_net(mask)) try: ip_set.add(IP(ip)) except: """单IP随意区间、单IP不标准区间""" if len(ip.split('.')) == 4: [ip_set.add(IP(x)) for x in split_star_and_sections(ip)] elif len(ip.split('.')) == 7 and '-' in ip: [ip_set.add(IP(x)) for x in split_ip_s_ip(ip)] else: raise ValueError('{} is a invalid ip like str'.format(ip)) return ip_set def get_ips(ip_list: list) -> list: result = [] ip_set = get_ip_set(ip_list) for ip_list in ip_set: for ip in ip_list: result.append(ip) return result # ########################判断是否存在ip包含关系######################### def is_overlap_internal_cidr(target): """判断所选IP、IP段中是否有保留地址""" res = [] for internal in INTERNAL_IP_LIST: if IP(target).overlaps(internal): res.append(INTERNAL_IP_LIST) return res or False # ########################format######################### def format_target(target_str: str): assets = [] for t in target_str.replace(',', ' ').replace(',', ' ').split(): if t.isdigit(): assets.append(str(IP(t))) elif is_ip(t): assets.append(t) elif is_ipv4_cidr(t): ip, mask = t.split('/') t = [str(x) for x in IP(ip).make_net(mask)] assets.extend(t) elif len(t.split('.')) == 4: assets.extend(split_star_and_sections(t)) elif len(t.split('.')) == 7 and '-' in t: assets.extend(split_ip_s_ip(t)) elif is_domain(t): assets.append(t) else: raise ValueError return ','.join(assets)
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/network/ip.py
ip.py
import re import requests import copy import os from urllib.parse import urlparse, urlunparse, parse_qs, urlencode, urljoin, quote, unquote from ..enums import PLACE from ..difinition import DEFAULT_GET_POST_DELIMITER, DEFAULT_COOKIE_DELIMITER from tld import get_tld import dns.resolver import socket import logging logger = logging.getLogger(__name__) def resolve_url(url): """处理url的模块,可以返回url的各种信息""" tld = get_tld(url, fix_protocol=True, as_object=True) return tld def format_url(url): from .ip import is_ip res = urlparse(url) scheme = res.scheme + '://' if res.scheme else 'http://' if res.scheme and not res.hostname: scheme = 'http://' if str(res.port) != '443' else 'https://' host = str(res.scheme) path = str(res.path) if res.scheme == 'http': port = str(res.port) if res.port else "80" else: port = str(res.port) if res.port else "443" elif res.scheme: if res.scheme == 'http': port = str(res.port) if res.port else "80" else: port = str(res.port) if res.port else "443" if '/' in str(res.hostname): host = str(res.hostname).split('/')[0] path = '/' + ''.join(str(res.hostname).split('/')[0:]) + str(res.path) else: host = str(res.hostname) path = str(res.path) else: port = str(res.port) if res.port else '80' if '/' in str(res.path): t = str(res.path).split('/') host = str(res.path).split('/')[0] path = '/' + ''.join(str(res.path).split('/')[1:]) else: host = res.path path = '' if is_ip(host): if path and path != '/': return scheme + host + path else: return scheme + host + ":" + port else: if host.startswith('www.'): r = scheme + host elif host.startswith('host.docker.internal'): if port != '80' and port != '443': r = scheme + host + ':' + port else: r = scheme + host else: r = scheme + 'www.' + host return r + path def switch_api_from_url(url, api_path): """ 更改api,保留其他参数 :param url: 原始url :param api_path: 新的api地址(不需要一开始的/) :return: """ res = urlparse(url) # scheme, netloc, path, params, query, fragment res_com = (res.scheme, res.netloc, api_path, res.params, res.query, res.fragment) res = urlunparse(res_com) return res def parse_params_for_url(url, dic): """在原有的url基础上增加新的query参数字典""" res = urlparse(url) query = urlencode(dic) res_com = (res.scheme, res.netloc, res.path, res.params, '{}&{}'.format(res.query, query), res.fragment) res = urlunparse(res_com) return res def get_parent_paths(path, domain=True): ''' 通过一个链接分离出各种目录 :param path: :param domain: :return: ''' netloc = '' if domain: p = urlparse(path) path = p.path netloc = "{}://{}".format(p.scheme, p.netloc) paths = [] if not path or path[0] != '/': return paths # paths.append(path) if path[-1] == '/': paths.append(netloc + path) tph = path if path[-1] == '/': tph = path[:-1] while tph: tph = tph[:tph.rfind('/') + 1] paths.append(netloc + tph) tph = tph[:-1] return paths def get_links(content, domain, limit=True): ''' 从网页源码中匹配链接 :param content: html源码 :param domain: 当前网址domain :param limit: 是否限定于此域名 :return: ''' p = urlparse(domain) netloc = "{}://{}{}".format(p.scheme, p.netloc, p.path) match = re.findall(r'''(href|src)=["'](.*?)["']''', content, re.S | re.I) urls = [] for i in match: _domain = urljoin(netloc, i[1]) if limit: if p.netloc.split(":")[0] not in _domain: continue urls.append(_domain) return urls def get_param_from_url(url, *args): """ 从url中通过指定参数获取参数的值 :param url:目标url :param args:填写想要获取参数值的key值,填写几个就会返回几个结果 :return:若存在,返回对应值(string型);若不存在,返回None e.g. """ params = parse_qs(urlparse(url).query) res = [] for item in args: try: tmp = params[item][0] res.append(tmp) except KeyError: res.append(None) return tuple(res) if len(res) > 1 else res[0] def get_ip_from_target(url): """通过url解析其ip""" # TODO 多个解析ip情况的处理 try: # 使用tld更好的处理url使其符合后续操作 tld = get_tld(url, fix_protocol=True, as_object=True) try: # 先使用socket.getaddrinfo查看是否可以直接gai到 myaddr = socket.getaddrinfo(tld.fld, tld.subdomain if tld.subdomain else 'http') # 处理点1 return myaddr[0][4][0] except socket.gaierror: # 若gai不到,则需要dns.resolver去反向解析 try: answers = dns.resolver.resolve(tld.fld, 'A') for rdata in answers: if rdata.address == '0.0.0.1': continue # 处理点2 return rdata.address except dns.resolver.NXDOMAIN as e: return None except Exception as e: # tld socket dnsresolver都有可能报错 logger.error(e, exc_info=True) return None def get_host_from_url(url): """从url中获取host""" return urlparse(url).hostname def prepare_url(url, params): """通过request的方式去实际获取该返回的url""" req = requests.Request('GET', url, params=params) r = req.prepare() return r.url def get_cname(domain, log_flag=True): cnames = [] try: answers = dns.resolver.query(domain, 'CNAME') for rdata in answers: cnames.append(str(rdata.target).strip(".").lower()) except dns.resolver.NoAnswer as e: if log_flag: logger.debug(e) except Exception as e: if log_flag: logger.warning("{} {}".format(domain, e)) return cnames def domain_parsed(domain, fail_silently=True): domain = domain.strip() try: res = get_tld(domain, fix_protocol=True, as_object=True) item = { "subdomain": res.subdomain, "domain": res.domain, "fld": res.fld } return item except Exception as e: if not fail_silently: raise e def is_in_scope(src_domain, target_domain): def get_fld(domain): res = domain_parsed(domain) if res: return res["fld"] fld1 = get_fld(src_domain) fld2 = get_fld(target_domain) if not fld1 or not fld2: return False if fld1 != fld2: return False if src_domain == target_domain: return True return src_domain.endswith("."+target_domain) def is_in_scopes(domain, scopes): for target_scope in scopes: if is_in_scope(domain, target_scope): return True return False def generateResponse(resp: requests.Response): response_raw = "HTTP/1.1 {} {}\r\n".format(resp.status_code, resp.reason) for k, v in resp.headers.items(): response_raw += "{}: {}\r\n".format(k, v) response_raw += "\r\n" response_raw += resp.text return response_raw def splitUrlPath(url, all_replace=True, flag='<--flag-->') -> list: '''' all_replace 默认为True 替换所有路径,False 在路径后面加 flag 要加入的标记符 ''' u = urlparse(url) path_split = u.path.split("/")[1:] path_split2 = [] for i in path_split: if i.strip() == "": continue path_split2.append(i) index = 0 result = [] for path in path_split2: copy_path_split = copy.deepcopy(path_split2) if all_replace: copy_path_split[index] = flag else: copy_path_split[index] = path + flag new_url = urlunparse([u.scheme, u.netloc, ('/' + '/'.join(copy_path_split)), u.params, u.query, u.fragment]) result.append(new_url) sptext = os.path.splitext(path) if sptext[1]: if all_replace: copy_path_split[index] = flag + sptext[1] else: copy_path_split[index] = sptext[0] + flag + sptext[1] new_url = urlunparse([u.scheme, u.netloc, ('/' + '/'.join(copy_path_split)), u.params, u.query, u.fragment]) result.append(new_url) index += 1 return result def url_dict2str(d: dict, position=PLACE.GET): if isinstance(d, str): return d temp = "" urlsafe = "!$%'()*+,/:;=@[]~" if position == PLACE.GET or position == PLACE.POST: for k, v in d.items(): temp += "{}={}{}".format(k, quote(v, safe=urlsafe), DEFAULT_GET_POST_DELIMITER) temp = temp.rstrip(DEFAULT_GET_POST_DELIMITER) elif position == PLACE.COOKIE: for k, v in d.items(): temp += "{}={}{} ".format(k, quote(v, safe=urlsafe), DEFAULT_COOKIE_DELIMITER) temp = temp.rstrip(DEFAULT_COOKIE_DELIMITER) return temp def json_to_str(s) -> str: ''' 表单转字符串 ''' return urlencode(s) def urlEncode(s) -> str: return quote(s) def urlDecode(s) -> str: return unquote(s)
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/network/url.py
url.py
import logging import math logger = logging.getLogger(__name__) data = { 'TOP_500_PORTS': "1,3-4,6-7,9,13,17,19-26,30,33,37,42,49,53,79-83,85,88,90,100,106,110-111,113,119,135,139,143-144,146,161,163,179,199,211,222,254-255,264,280,306,311,340,366,389,407,427,443-445,464-465,497,500,512-515,541,543-544,548,554,563,587,593,625,631,636,646,648,705,711,787,800,808,873,880,888,900-902,912,987,990,992-993,995,999-1000,1002,1022-1075,1077-1083,1085-1086,1088,1093-1094,1096-1100,1104,1106-1108,1110-1111,1148,1169,1218,1234,1248,1272,1310-1311,1352,1433,1494,1500-1501,1503,1521,1666,1687,1700,1717-1718,1720,1723,1755,1761,1783,1801,1840,1863-1864,1900,1935,1947,1998,2000-2010,2030,2049,2065,2100,2103,2105,2107,2119,2121,2135,2144,2160-2161,2190,2222,2260,2301,2381,2383,2399,2401,2492,2500,2525,2601-2602,2604-2605,2607,2701-2702,2717-2718,2809,2811,2869,2875,2967,3000-3001,3005,3017,3031,3052,3071,3128,3211,3260,3268-3269,3283,3300-3301,3306,3323,3325,3333,3351,3367,3389,3404,3476,3551,3580,3659,3689-3690,3703,3766,3784,3801,3827,3986,3998,4000-4003,4045,4126,4129,4242,4443-4444,4449,4662,4899,5000-5004,5009,5030,5050-5051,5060,5100-5102,5120,5190,5214,5222,5225-5226,5269,5357,5414,5431-5432,5500,5550,5555,5566,5631,5633,5666,5679,5718,5800-5801,5810,5825,5877,5900-5902,5910-5911,5925,5959-5962,5987-5989,6000-6002,6004-6005,6059,6101,6112,6123,6129,6156,6389,6543,6580,6646,6666-6667,6788-6789,6881,6901,6969,7000-7001,7019,7070,7100,7106,7200,7625,7627,7741,7777-7778,7911,7937-7938,8000-8002,8007-8010,8021,8031,8080-8089,8181,8192-8194,8222,8291,8333,8400,8402,8443,8600,8649,8651-8652,8701,8873,8888,8899,8994,9000-9002,9009,9050,9071,9090,9100-9102,9207,9415,9535,9593-9595,9876,9999-10001,10010,10243,12000,12345,13782-13783,14238,15000,16992-16993,20005,20828,23502,27000,32768-32775,33354,35500,42510,45100,49152-49157,49999-50001,51103,52822,52869,55555,55600,64623,64680,65000,65389", 'TOP_1000_PORTS': "1,3-4,6-7,9,13,17,19-26,30,32-33,37,42-43,49,53,70,79-85,88-90,99-100,106,109-111,113,119,125,135,139,143-144,146,161,163,179,199,211-212,222,254-256,259,264,280,301,306,311,340,366,389,406-407,416-417,425,427,443-445,458,464-465,481,497,500,512-515,524,541,543-545,548,554-555,563,587,593,616-617,625,631,636,646,648,666-668,683,687,691,700,705,711,714,720,722,726,749,765,777,783,787,800-801,808,843,873,880,888,898,900-903,911-912,981,987,990,992-993,995,999-1002,1007,1009-1011,1021-1100,1102,1104-1108,1110-1114,1117,1119,1121-1124,1126,1130-1132,1137-1138,1141,1145,1147-1149,1151-1152,1154,1163-1166,1169,1174-1175,1183,1185-1187,1192,1198-1199,1201,1213,1216-1218,1233-1234,1236,1244,1247-1248,1259,1271-1272,1277,1287,1296,1300-1301,1309-1311,1322,1328,1334,1352,1417,1433-1434,1443,1455,1461,1494,1500-1501,1503,1521,1524,1533,1556,1580,1583,1594,1600,1641,1658,1666,1687-1688,1700,1717-1721,1723,1755,1761,1782-1783,1801,1805,1812,1839-1840,1862-1864,1875,1900,1914,1935,1947,1971-1972,1974,1984,1998-2010,2013,2020-2022,2030,2033-2035,2038,2040-2043,2045-2049,2065,2068,2099-2100,2103,2105-2107,2111,2119,2121,2126,2135,2144,2160-2161,2170,2179,2190-2191,2196,2200,2222,2251,2260,2288,2301,2323,2366,2381-2383,2393-2394,2399,2401,2492,2500,2522,2525,2557,2601-2602,2604-2605,2607-2608,2638,2701-2702,2710,2717-2718,2725,2800,2809,2811,2869,2875,2909-2910,2920,2967-2968,2998,3000-3001,3003,3005-3007,3011,3013,3017,3030-3031,3052,3071,3077,3128,3168,3211,3221,3260-3261,3268-3269,3283,3300-3301,3306,3322-3325,3333,3351,3367,3369-3372,3389-3390,3404,3476,3493,3517,3527,3546,3551,3580,3659,3689-3690,3703,3737,3766,3784,3800-3801,3809,3814,3826-3828,3851,3869,3871,3878,3880,3889,3905,3914,3918,3920,3945,3971,3986,3995,3998,4000-4006,4045,4111,4125-4126,4129,4224,4242,4279,4321,4343,4443-4446,4449,4550,4567,4662,4848,4899-4900,4998,5000-5004,5009,5030,5033,5050-5051,5054,5060-5061,5080,5087,5100-5102,5120,5190,5200,5214,5221-5222,5225-5226,5269,5280,5298,5357,5405,5414,5431-5432,5440,5500,5510,5544,5550,5555,5560,5566,5631,5633,5666,5678-5679,5718,5730,5800-5802,5810-5811,5815,5822,5825,5850,5859,5862,5877,5900-5904,5906-5907,5910-5911,5915,5922,5925,5950,5952,5959-5963,5987-5989,5998-6007,6009,6025,6059,6100-6101,6106,6112,6123,6129,6156,6346,6389,6502,6510,6543,6547,6565-6567,6580,6646,6666-6669,6689,6692,6699,6779,6788-6789,6792,6839,6881,6901,6969,7000-7002,7004,7007,7019,7025,7070,7100,7103,7106,7200-7201,7402,7435,7443,7496,7512,7625,7627,7676,7741,7777-7778,7800,7911,7920-7921,7937-7938,7999-8002,8007-8011,8021-8022,8031,8042,8045,8080-8090,8093,8099-8100,8180-8181,8192-8194,8200,8222,8254,8290-8292,8300,8333,8383,8400,8402,8443,8500,8600,8649,8651-8652,8654,8701,8800,8873,8888,8899,8994,9000-9003,9009-9011,9040,9050,9071,9080-9081,9090-9091,9099-9103,9110-9111,9200,9207,9220,9290,9415,9418,9485,9500,9502-9503,9535,9575,9593-9595,9618,9666,9876-9878,9898,9900,9917,9929,9943-9944,9968,9998-10004,10009-10010,10012,10024-10025,10082,10180,10215,10243,10566,10616-10617,10621,10626,10628-10629,10778,11110-11111,11967,12000,12174,12265,12345,13456,13722,13782-13783,14000,14238,14441-14442,15000,15002-15004,15660,15742,16000-16001,16012,16016,16018,16080,16113,16992-16993,17877,17988,18040,18101,18988,19101,19283,19315,19350,19780,19801,19842,20000,20005,20031,20221-20222,20828,21571,22939,23502,24444,24800,25734-25735,26214,27000,27352-27353,27355-27356,27715,28201,30000,30718,30951,31038,31337,32768-32785,33354,33899,34571-34573,35500,38292,40193,40911,41511,42510,44176,44442-44443,44501,45100,48080,49152-49161,49163,49165,49167,49175-49176,49400,49999-50003,50006,50300,50389,50500,50636,50800,51103,51493,52673,52822,52848,52869,54045,54328,55055-55056,55555,55600,56737-56738,57294,57797,58080,60020,60443,61532,61900,62078,63331,64623,64680,65000,65129,65389", 'TOP_2000_PORTS': '1,3-4,6-7,9,13,17,19-27,30,32-33,37,42-43,49,53,55,57,59,70,77,79-90,98-100,102,106,109-111,113,119,123,125,127,135,139,143-144,146,157,161,163,179,199,210-212,220,222-223,225,250-252,254-257,259,264,280,301,306,311,333,340,366,388-389,406-407,411,416-417,419,425,427,441-445,447,458,464-465,475,481,497,500,502,512-515,523-524,540-541,543-545,548,554-557,563,587,593,600,602,606,610,616-617,621,623,625,631,636,639,641,646,648,655,657,659-660,666-669,674,683-684,687,690-691,700-701,705,709-711,713-715,720,722,725-726,728-732,740,748-749,754,757-758,765,777-778,780,782-783,786-787,790,792,795,800-803,805-806,808,822-823,825,829,839-840,843,846,856,859,862,864,873-874,878,880,888,898,900-905,911-913,918,921-922,924,928,930-931,943,953,969,971,980-981,987,990,992-993,995-996,998-1002,1004-1015,1020-1114,1116-1119,1121-1128,1130-1132,1134-1138,1141,1143-1145,1147-1154,1156-1159,1162-1169,1173-1176,1179-1180,1182-1188,1190-1192,1194-1196,1198-1201,1204,1207-1213,1215-1218,1220-1223,1228-1229,1233-1234,1236,1239-1241,1243-1244,1247-1251,1259,1261-1262,1264,1268,1270-1272,1276-1277,1279,1282,1287,1290-1291,1296-1297,1299-1303,1305-1311,1314-1319,1321-1322,1324,1327-1328,1330-1331,1334,1336-1337,1339-1340,1347,1350-1353,1357,1413-1414,1417,1433-1434,1443,1455,1461,1494,1500-1501,1503,1516,1521-1522,1524-1526,1533,1547,1550,1556,1558-1560,1565-1566,1569,1580,1583-1584,1592,1594,1598,1600,1605,1607,1615,1620,1622,1632,1635,1638,1641,1645,1658,1666,1677,1683,1687-1688,1691,1694,1699-1701,1703,1707-1709,1711-1713,1715,1717-1723,1730,1735-1736,1745,1750,1752-1753,1755,1761,1782-1783,1791-1792,1799-1801,1805-1808,1811-1812,1823,1825,1835,1839-1840,1858,1861-1864,1871,1875,1883,1900-1901,1911-1912,1914,1918,1924,1927,1935,1947,1954,1958,1971-1976,1981,1984,1998-2013,2020-2022,2025,2030-2031,2033-2035,2038,2040-2049,2062,2065,2067-2070,2080-2083,2086-2087,2095-2096,2099-2101,2103-2107,2111-2112,2115,2119,2121,2124,2126,2134-2135,2142,2144,2148,2150,2160-2161,2170,2179,2187,2190-2191,2196-2197,2200-2201,2203,2222,2224,2232,2241,2250-2251,2253,2260-2262,2265,2269-2271,2280,2288,2291-2292,2300-2302,2304,2312-2313,2323,2325-2326,2330,2335,2340,2366,2371-2372,2375-2376,2381-2383,2391,2393-2394,2399,2401,2418,2425,2433,2435-2436,2438-2439,2449,2456,2463,2472,2492,2500-2501,2505,2522,2525,2531-2532,2550-2551,2557-2558,2567,2580,2583-2584,2598,2600-2602,2604-2608,2622-2623,2628,2631,2638,2644,2691,2700-2702,2706,2710-2712,2717-2718,2723,2725,2728,2734,2800,2804,2806,2809,2811-2812,2847,2850,2869,2875,2882,2888-2889,2898,2901-2903,2908-2910,2920,2930,2957-2958,2967-2968,2973,2984,2987-2988,2991,2997-2998,3000-3003,3005-3007,3011,3013-3014,3017,3023,3025,3030-3031,3050,3052,3057,3062-3063,3071,3077,3080,3089,3102-3103,3118-3119,3121,3128,3146,3162,3167-3168,3190,3200,3210-3211,3220-3221,3240,3260-3261,3263,3268-3269,3280-3281,3283,3291,3299-3301,3304,3306-3307,3310-3311,3319,3322-3325,3333-3334,3351,3362-3363,3365,3367-3372,3374,3376,3388-3390,3396,3399-3400,3404,3410,3414-3415,3419,3425,3430,3439,3443,3456,3476,3479,3483,3485-3486,3493,3497,3503,3505-3506,3511,3513-3515,3517,3519-3520,3526-3527,3530,3532,3546,3551,3577,3580,3586,3599-3600,3602-3603,3621-3622,3632,3636-3637,3652-3653,3656,3658-3659,3663,3669-3670,3672,3680-3681,3683-3684,3689-3690,3697,3700,3703,3712,3728,3731,3737,3742,3749,3765-3766,3784,3787-3788,3790,3792-3793,3795-3796,3798-3801,3803,3806,3808-3814,3817,3820,3823-3828,3830-3831,3837,3839,3842,3846-3853,3856,3859-3860,3863,3868-3872,3876,3878-3880,3882,3888-3890,3897,3899,3901-3902,3904-3909,3911,3913-3916,3918-3920,3922-3923,3928-3931,3935-3937,3940-3941,3943-3946,3948-3949,3952,3956-3957,3961-3964,3967-3969,3971-3972,3975,3979-3983,3986,3989-4007,4009-4010,4016,4020,4022,4024-4025,4029,4035-4036,4039-4040,4045,4056,4058,4065,4080,4087,4090,4096,4100-4101,4111-4113,4118-4121,4125-4126,4129,4135,4141,4143,4147,4158,4161,4164,4174,4190,4192,4200,4206,4220,4224,4234,4242-4243,4252,4262,4279,4294,4297-4298,4300,4302,4321,4325,4328,4333,4342-4343,4355-4358,4369,4374-4376,4384,4388,4401,4407,4414-4415,4418,4430,4433,4442-4447,4449,4454,4464,4471,4476,4516-4517,4530,4534,4545,4550,4555,4558-4559,4567,4570,4599-4602,4606,4609,4644,4649,4658,4662,4665,4687,4689,4700,4712-4713,4745,4760,4767,4770-4771,4778,4793,4800,4819,4848,4859-4860,4875-4877,4881,4899-4900,4903,4912,4931,4949,4998-5005,5009-5017,5020-5021,5023,5030,5033,5040,5050-5055,5060-5061,5063,5066,5070,5074,5080-5081,5087-5088,5090,5095-5096,5098,5100-5102,5111,5114,5120-5122,5125,5133,5137,5147,5151-5152,5190,5200-5202,5212,5214,5219,5221-5223,5225-5226,5233-5235,5242,5250,5252,5259,5261,5269,5279-5280,5291,5298,5339,5347,5353,5357,5370,5377,5405,5414,5423,5431-5433,5440-5442,5444,5457-5458,5473,5475,5500-5501,5510,5520,5544,5550,5555,5560,5566,5631,5633,5666,5678-5680,5718,5730,5800-5803,5807,5810-5812,5815,5818,5822-5823,5825,5850,5859,5862,5868-5869,5877,5899-5907,5909-5911,5914-5915,5918,5922,5925,5938,5940,5950,5952,5959-5963,5968,5981,5987-5989,5998-6009,6017,6025,6050-6051,6059-6060,6068,6100-6101,6103,6106,6112,6123,6129,6156,6203,6222,6247,6346,6389,6481,6500,6502,6504,6510,6520,6543,6547,6550,6565-6567,6580,6600,6646,6662,6666-6670,6689,6692,6699,6711,6732,6779,6788-6789,6792,6839,6881,6896,6901,6969,7000-7004,7007,7010,7019,7024-7025,7050-7051,7070,7080,7100,7103,7106,7123,7200-7201,7241,7272,7278,7281,7402,7435,7438,7443,7496,7512,7625,7627,7676,7725,7741,7744,7749,7770,7777-7778,7800,7878,7900,7911,7913,7920-7921,7929,7937-7938,7999-8002,8007-8011,8015-8016,8019,8021-8022,8031,8042,8045,8050,8080-8090,8093,8095,8097-8100,8118,8180-8181,8189,8192-8194,8200,8222,8254,8290-8294,8300,8333,8383,8385,8400,8402,8443,8481,8500,8540,8600,8648-8649,8651-8652,8654,8675-8676,8686,8701,8765-8766,8800,8873,8877,8888-8889,8899,8987,8994,8996,9000-9003,9009-9011,9040,9050,9071,9080-9081,9090-9091,9098-9103,9110-9111,9152,9191,9197-9198,9200,9207,9220,9290,9409,9415,9418,9443-9444,9485,9500-9503,9535,9575,9593-9595,9600,9618,9621,9643,9666,9673,9815,9876-9878,9898,9900,9914,9917,9929,9941,9943-9944,9968,9988,9992,9998-10005,10008-10012,10022-10025,10034,10058,10082-10083,10160,10180,10215,10243,10566,10616-10617,10621,10626,10628-10629,10778,10873,11110-11111,11967,12000,12006,12021,12059,12174,12215,12262,12265,12345-12346,12380,12452,13456,13722,13724,13782-13783,14000,14238,14441-14442,15000-15004,15402,15660,15742,16000-16001,16012,16016,16018,16080,16113,16705,16800,16851,16992-16993,17595,17877,17988,18000,18018,18040,18101,18264,18988,19101,19283,19315,19350,19780,19801,19842,19900,20000,20002,20005,20031,20221-20222,20828,21571,21792,22222,22939,23052,23502,23796,24444,24800,25734-25735,26000,26214,26470,27000,27352-27353,27355-27357,27715,28201,28211,29672,29831,30000,30005,30704,30718,30951,31038,31337,31727,32768-32785,32791-32792,32803,32816,32822,32835,33354,33453,33554,33899,34571-34573,35500,35513,37839,38037,38185,38188,38292,39136,39376,39659,40000,40193,40811,40911,41064,41511,41523,42510,44176,44334,44442-44443,44501,44709,45100,46200,46996,47544,48080,49152-49161,49163-49165,49167-49168,49171,49175-49176,49186,49195,49236,49400-49401,49999-50003,50006,50050,50300,50389,50500,50636,50800,51103,51191,51413,51493,52660,52673,52710,52735,52822,52847-52851,52853,52869,53211,53313-53314,53535,54045,54328,55020,55055-55056,55555,55576,55600,56737-56738,57294,57665,57797,58001-58002,58080,58630,58632,58838,59110,59200-59202,60020,60123,60146,60443,60642,61532,61613,61900,62078,63331,64623,64680,65000,65129,65310,65389', 'TOP_5000_PORTS': "1-35,37-226,228-231,233-238,242-271,273,276-277,280-284,286-289,293-295,300-301,303,305-306,308-326,329,333-334,336-337,340,343-916,918-939,941-1894,1896-2193,2196-2225,2232,2241,2250-2251,2253,2260-2262,2265,2269-2271,2280,2288,2291-2292,2300-2302,2304,2307,2312-2313,2323,2325-2326,2330,2335,2340,2366,2371-2372,2375-2376,2381-2383,2391,2393-2394,2399,2401,2418,2425,2430-2433,2435-2436,2438-2439,2449,2456,2463,2472,2492,2500-2501,2505,2522,2525,2531-2532,2550-2551,2557-2558,2564,2567,2580,2583-2584,2598,2600-2602,2604-2608,2622-2623,2627-2628,2631,2638,2644,2691,2700-2702,2706,2710-2712,2717-2718,2723,2725,2728,2734,2766,2800,2804,2806,2809,2811-2812,2847,2850,2869,2875,2882,2888-2889,2898,2901-2903,2908-2910,2920,2930,2957-2958,2967-2968,2973,2984,2987-2988,2991,2997-2998,3000-3003,3005-3007,3011,3013-3014,3017,3023,3025,3030-3031,3045,3049-3050,3052,3057,3062-3064,3071,3077,3080,3086,3089,3102-3103,3118-3119,3121,3128,3141,3146,3162,3167-3168,3190,3200,3210-3211,3220-3221,3240,3260-3261,3263-3264,3268-3269,3280-3281,3283,3291-3292,3299-3301,3304,3306-3307,3310-3311,3319,3322-3325,3333-3334,3351,3362-3363,3365,3367-3372,3374,3376,3388-3390,3396-3400,3404,3410,3414-3415,3419,3421,3425,3430,3439,3443,3456-3457,3476,3479,3483,3485-3486,3493,3497,3503,3505-3506,3511,3513-3515,3517,3519-3520,3526-3527,3530-3532,3546,3551,3577,3580,3586,3599-3600,3602-3603,3621-3622,3632,3636-3637,3652-3653,3656,3658-3659,3663,3669-3670,3672,3680-3681,3683-3684,3689-3690,3697,3700,3703,3712,3728,3731,3737,3742,3749,3765-3766,3784,3787-3788,3790,3792-3793,3795-3796,3798-3801,3803,3806,3808-3814,3817,3820,3823-3828,3830-3831,3837,3839,3842,3846-3853,3856,3859-3860,3863,3868-3872,3876,3878-3880,3882,3888-3890,3897,3899-3902,3904-3909,3911,3913-3916,3918-3920,3922-3923,3928-3931,3935-3937,3940-3941,3943-3946,3948-3949,3952,3956-3957,3961-3964,3967-3969,3971-3972,3975,3979-3986,3989-4010,4016,4020,4022,4024-4025,4029,4035-4036,4039-4040,4045,4056,4058,4065,4080,4087,4090,4096,4100-4101,4111-4113,4118-4121,4125-4126,4129,4132-4133,4135,4141,4143-4144,4147,4158,4161,4164,4174,4190,4192,4199-4200,4206,4220,4224,4234,4242-4243,4252,4262,4279,4294,4297-4298,4300,4302,4321,4325,4328,4333,4342-4343,4355-4358,4369,4374-4376,4384,4388,4401,4407,4414-4415,4418,4430,4433,4442-4447,4449,4454,4464,4471,4476,4480,4500,4516-4517,4530,4534,4545,4550,4555,4557-4559,4567,4570,4599-4602,4606,4609,4644,4649,4658,4660,4662,4665,4672,4687,4689,4700,4712-4713,4745,4760,4767,4770-4771,4778,4793,4800,4819,4848,4859-4860,4875-4877,4881,4899-4900,4903,4912,4931,4949,4987,4998-5005,5009-5017,5020-5021,5023,5030,5033,5040,5050-5055,5060-5061,5063,5066,5070,5074,5080-5081,5087-5088,5090,5095-5096,5098,5100-5102,5111,5114,5120-5122,5125,5133,5137,5145,5147,5151-5152,5190-5191,5193,5200-5202,5212,5214,5219,5221-5223,5225-5226,5232-5235,5242,5250,5252,5259,5261,5269,5279-5280,5291,5298,5300-5303,5308,5339,5347,5353,5357,5370,5377,5400,5405,5414,5423,5431-5433,5440-5442,5444,5457-5458,5473,5475,5490,5500-5502,5510,5520,5530,5544,5550,5552-5555,5557,5560,5566,5580-5581,5611-5612,5620-5622,5631-5633,5665-5667,5672,5678-5680,5711,5713-5714,5717-5718,5721-5723,5730,5732,5734,5737,5800-5804,5806-5808,5810-5812,5814-5815,5817-5818,5820-5827,5831,5834,5836,5838-5840,5845,5848-5850,5852-5854,5858-5860,5862,5868-5869,5871,5874-5875,5877-5878,5881,5887-5888,5899-5912,5914-5915,5917-5918,5920-5927,5931,5934,5936,5938-5940,5945,5948-5950,5952-5954,5958-5963,5966,5968-5969,5971,5974-5975,5977-5978,5981,5985-5989,5997-6010,6015,6017,6021,6025,6030,6050-6052,6055,6059-6060,6062-6063,6065,6067-6068,6077,6085,6090-6091,6100-6101,6103,6105-6106,6110-6113,6115,6120,6123,6126,6129,6141-6143,6145-6147,6156,6161,6203,6222,6247,6250-6251,6259,6273-6274,6309-6310,6323-6324,6346-6347,6349-6350,6379,6389,6400-6401,6412,6481,6500,6502-6504,6510,6520,6535,6543-6544,6547-6548,6550,6565-6567,6579-6580,6588,6600,6606,6619,6628,6644,6646-6647,6650,6662,6665-6670,6689,6692,6699-6701,6709-6711,6725,6732,6734,6779-6780,6788-6789,6792,6839,6877,6881,6888,6896-6897,6901,6920,6922,6942,6956,6969,6972-6973,7000-7010,7019,7024-7025,7033,7043,7050-7051,7067-7068,7070-7072,7080,7092,7099-7104,7106,7119,7121,7123,7184,7200-7201,7218,7231,7241,7272-7273,7278,7281,7300,7320,7325-7326,7345,7400,7402,7435,7438,7443,7451,7456,7464,7496,7500-7501,7512,7553,7555,7597,7600,7625,7627-7628,7634,7637,7654,7676,7685,7688,7725,7741,7744,7749,7770-7772,7777-7778,7780,7788-7789,7800,7813,7830,7852-7854,7878,7895,7900,7911,7913,7920-7921,7929,7937-7938,7975,7998-8003,8005-8011,8014-8016,8018-8019,8021-8023,8025,8029,8031,8037,8042,8045,8050,8052,8060,8064,8076,8080-8090,8092-8093,8095,8097-8100,8110,8116,8118,8123,8133,8144,8180-8181,8189,8192-8194,8200-8202,8222,8232,8245,8248,8254-8255,8268,8273,8282,8290-8295,8300,8308,8333,8339,8383,8385,8400-8403,8409,8443,8445,8451-8455,8470-8472,8474,8477,8479,8481,8484,8500,8515,8530-8531,8539-8540,8562,8600-8601,8621,8640,8644,8648-8649,8651-8652,8654-8655,8658,8673,8675-8676,8680,8686,8701,8736,8752,8756,8765-8766,8770,8772,8790,8798,8800-8801,8843,8865,8873,8877-8880,8882-8883,8887-8889,8892,8898-8900,8925,8954,8980,8987,8994,8996,8999-9005,9009-9011,9013,9020-9022,9037,9040,9044,9050-9051,9061,9065,9071,9080-9081,9084,9090-9091,9098-9107,9110-9111,9125,9128,9130-9131,9133,9152,9160-9161,9170,9183,9191,9197-9198,9200,9202,9207,9210-9211,9220,9287,9290,9300,9333,9343,9351,9364,9400,9409,9415,9418,9443-9444,9454,9464,9478,9485,9493,9500-9503,9513,9527,9535,9575,9583,9592-9595,9600,9613,9616,9618-9621,9628,9643,9648,9654,9661,9665-9667,9673-9674,9679-9680,9683,9694,9700,9745,9777,9812,9814-9815,9823,9825-9826,9830,9844,9875-9878,9898,9900-9901,9908-9912,9914-9915,9917,9919,9929,9941,9943-9944,9950,9968,9971,9975,9979,9988,9990-9992,9995,9998-10012,10018-10020,10022-10025,10034-10035,10042,10045,10058,10064,10082-10083,10093,10101,10115,10160,10180,10215,10238,10243,10245-10246,10255,10280,10338,10347,10357,10387,10414,10443,10494,10500,10509,10529,10535,10550-10556,10565-10567,10601-10602,10616-10617,10621,10626,10628-10629,10699,10754,10778,10842,10852,10873,10878,10900,11000-11001,11003,11007,11019,11026,11031-11033,11089,11100,11110-11111,11180,11200,11224,11250,11288,11296,11371,11401,11552,11697,11735,11813,11862-11863,11940,11967,12000-12002,12005-12006,12009,12019,12021,12031,12034,12059,12077,12080,12090,12096-12097,12121,12132,12137,12146,12156,12171,12174,12192,12215,12225,12240,12243,12251,12262,12265,12271,12275,12296,12340,12345-12346,12380,12414,12452,12699,12702,12766,12865,12891-12892,12955,12962,13017,13093,13130,13132,13140,13142,13149,13167,13188,13192-13194,13229,13250,13261,13264-13265,13306,13318,13340,13359,13456,13502,13580,13695,13701,13713-13715,13718,13720-13724,13730,13766,13782-13784,13846,13899,14000-14001,14141,14147,14218,14237-14238,14254,14418,14441-14444,14534,14545,14693,14733,14827,14891,14916,15000-15005,15050,15145,15151,15190-15191,15275,15317,15344,15402,15448,15550,15631,15645-15646,15660,15670,15677,15722,15730,15742,15758,15915,16000-16001,16012,16016,16018,16048,16080,16113,16161,16270,16273,16283,16286,16297,16349,16372,16444,16464,16705,16723-16725,16797,16800,16845,16851,16900-16901,16992-16993,17007,17016-17017,17070,17089,17129,17251,17255,17300,17409,17413,17500,17595,17700-17702,17715,17801-17802,17860,17867,17877,17969,17985,17988,17997,18000,18012,18015,18018,18040,18080,18101,18148,18181-18184,18187,18231,18264,18333,18336-18337,18380,18439,18505,18517,18569,18669,18874,18887,18910,18962,18988,19010,19101,19130,19150,19200-19201,19283,19315,19333,19350,19353,19403,19464,19501,19612,19634,19715,19780,19801,19842,19852,19900,19995-19996,20000-20002,20005,20011,20017,20021,20031-20032,20039,20052,20076,20080,20085,20089,20102,20106,20111,20118,20125,20127,20147,20179-20180,20221-20228,20280,20473,20734,20828,20883,20934,20940,20990,21011,21078,21201,21473,21571,21631,21634,21728,21792,21891,21915,22022,22063,22100,22125,22128,22177,22200,22222-22223,22273,22290,22341,22350,22555,22563,22711,22719,22727,22769,22882,22939,22959,22969,23017,23040,23052,23219,23228,23270,23296,23342,23382,23430,23451,23502,23723,23796,23887,23953,24218,24392,24416,24444,24552,24554,24616,24800,24999-25001,25174,25260,25262,25288,25327,25445,25473,25486,25565,25703,25717,25734-25735,25847,26000-26001,26007,26208,26214,26340,26417,26470,26669,26972,27000-27003,27005,27007,27009-27010,27015-27019,27055,27074-27075,27087,27204,27316,27350-27353,27355-27357,27372,27374,27521,27537,27665,27715,27770,28017,28114,28142,28201,28211,28374,28567,28717,28850-28851,28924,28967,29045,29152,29243,29507,29672,29810,29831,30000-30001,30005,30087,30195,30299,30519,30599,30644,30659,30704-30705,30718,30896,30951,31033,31038,31058,31072,31337,31339,31386,31416,31438,31522,31657,31727-31728,32006,32022,32031,32088,32102,32200,32219,32260-32261,32764-32765,32767-32792,32797-32799,32803,32807,32814-32816,32820,32822,32835,32837,32842,32858,32868-32869,32871,32888,32897-32898,32904-32905,32908,32910-32911,32932,32944,32960-32961,32976,33000,33011,33017,33070,33087,33124,33175,33192,33200,33203,33277,33327,33335,33337,33354,33367,33395,33444,33453,33522-33523,33550,33554,33604-33605,33841,33879,33882,33889,33895,33899,34021,34036,34096,34189,34317,34341,34381,34401,34507,34510,34571-34573,34683,34728,34765,34783,34833,34875,35033,35050,35116,35131,35217,35272,35349,35392-35393,35401,35500,35506,35513,35553,35593,35731,35879,35900-35901,35906,35929,35986,36046,36104-36105,36256,36275,36368,36436,36508,36530,36552,36659,36677,36694,36710,36748,36823-36824,36914,36950,36962,36983,37121,37151,37174,37185,37218,37393,37522,37607,37614,37647,37674,37777,37789,37839,37855,38029,38037,38185,38188,38194,38205,38224,38270,38292,38313,38331,38358,38446,38481,38546,38561,38570,38761,38764,38780,38805,38936,39067,39117,39136,39265,39293,39376,39380,39433,39482,39489,39630,39659,39732,39763,39774,39795,39869,39883,39895,39917,40000-40003,40005,40011,40193,40306,40393,40400,40457,40489,40513,40614,40628,40712,40732,40754,40811-40812,40834,40911,40951,41064,41123,41142,41250,41281,41318,41342,41345,41348,41398,41442,41511,41523,41551,41632,41773,41794-41795,41808,42001,42035,42127,42158,42251,42276,42322,42449,42452,42510,42559-42560,42575,42590,42632,42675,42679,42685,42735,42906,42990,43000,43002,43018,43027,43103,43139,43143,43188,43212,43231,43242,43425,43654,43690,43734,43823,43868,44004,44101,44119,44176,44200,44334,44380,44410,44431,44442-44443,44479,44501,44505,44541,44616,44628,44704,44709,44711,44965,44981,45038,45050,45100,45136,45164,45220,45226,45413,45438,45463,45602,45624,45697,45777,45864,45960,46034,46069,46115,46171,46182,46200,46310,46372,46418,46436,46593,46813,46992,46996,47012,47029,47119,47197,47267,47348,47372,47448,47544,47557,47567,47581,47595,47624,47634,47700,47777,47806,47850,47858,47860,47966,47969,48009,48067,48080,48083,48127,48153,48167,48356,48434,48619,48631,48648,48682,48783,48813,48925,48966-48967,48973,49002,49048,49132,49152-49161,49163-49173,49175-49176,49179,49186,49189-49191,49195-49197,49201-49204,49211,49213,49216,49228,49232,49235-49236,49241,49275,49302,49352,49372,49398,49400-49401,49452,49498,49500,49519-49522,49597,49603,49678,49751,49762,49765,49803,49927,49999-50003,50006,50016,50019,50040,50050,50101,50189,50198,50202,50205,50224,50246,50258,50277,50300,50356,50389,50500,50513,50529,50545,50576-50577,50585,50636,50692,50733,50787,50800,50809,50815,50831,50833-50836,50849,50854,50887,50903,50945,50997,51011,51020,51037,51067,51103,51118,51139,51191,51233-51235,51240,51300,51343,51351,51366,51413,51423,51460,51484-51485,51488,51493,51515,51582,51658,51771-51772,51800,51809,51906,51909,51961,51965,52000-52003,52025,52046,52071,52173,52225-52226,52230,52237,52262,52391,52477,52506,52573,52660,52665,52673,52675,52710,52735,52822,52847-52851,52853,52869,52893,52948,53085,53178,53189,53211-53212,53240,53313-53314,53319,53361,53370,53460,53469,53491,53535,53633,53639,53656,53690,53742,53782,53827,53852,53910,53958,54045,54075,54101,54127,54235,54263,54276,54320-54321,54323,54328,54514,54551,54605,54658,54688,54722,54741,54873,54907,54987,54991,55000,55020,55055-55056,55183,55187,55227,55312,55350,55382,55400,55426,55479,55527,55555-55556,55568-55569,55576,55579,55600,55635,55652,55684,55721,55758,55773,55781,55901,55907,55910,55948,56016,56055,56259,56293,56507,56535,56591,56668,56681,56723,56725,56737-56738,56810,56822,56827,56973,56975,57020,57103,57123,57294,57325,57335,57347,57350,57352,57387,57398,57479,57576,57665,57678,57681,57702,57730,57733,57797,57891,57896,57923,57928,57988,57999,58001-58002,58072,58080,58107,58109,58164,58252,58305,58310,58374,58430,58446,58456,58468,58498,58562,58570,58610,58622,58630,58632,58634,58699,58721,58838,58908,58970,58991,59087,59107,59110,59122,59149,59160,59191,59200-59202,59239,59340,59499,59504,59509-59510,59525,59565,59684,59778,59810,59829,59841,59987,60000,60002-60003,60020,60055,60086,60111,60123,60146,60177,60227,60243,60279,60377,60401,60403,60443,60485,60492,60504,60544,60579,60612,60621,60628,60642,60713,60728,60743,60753,60782-60783,60789,60794,60989,61159,61169-61170,61402,61473,61516,61532,61613,61616-61617,61669,61722,61734,61827,61851,61900,61942,62006,62042,62078,62080,62188,62312,62519,62570,62674,62866,63105,63156,63331,63423,63675,63803,64080,64127,64320,64438,64507,64551,64623,64680,64726-64727,64890,65000,65048,65129,65301,65310-65311,65389,65488,65514", 'TOP_10000_PORTS': "1-35,37-226,228-231,233-238,242-271,273,276-277,280-284,286-289,293-295,300-301,303,305-306,308-326,329,333-334,336-337,340,343-916,918-939,941-1894,1896-2193,2196-2368,2370-2377,2379-2681,2683-2692,2694-2793,2795-2824,2826-2872,2874-2924,2926-3091,3093-3096,3098-3125,3127-3402,3404-3693,3695-4047,4049-4193,4197,4199-4314,4316,4320-4336,4340-4362,4366,4368-4379,4384,4388-4396,4400-4423,4425-4433,4441-4458,4464,4471,4476,4480,4484-4488,4500,4502,4516-4517,4530,4534-4538,4545-4559,4563,4566-4570,4573,4590-4606,4609,4621,4644,4649,4658-4692,4700-4704,4711-4713,4725-4733,4737-4747,4749-4756,4760,4767,4770-4771,4774,4778,4784-4791,4793,4800-4804,4819,4827,4837-4851,4859-4860,4867-4871,4875-4885,4888-4889,4894,4899-4903,4912-4915,4931,4936-4937,4940-4942,4949-4953,4969-4971,4980,4984-4991,4998-5017,5020-5034,5040,5042-5075,5078-5088,5090,5092-5096,5098-5107,5111-5112,5114-5117,5120-5122,5125,5133-5137,5145-5147,5150-5157,5161-5168,5172,5190-5197,5200-5203,5209,5212,5214-5215,5219,5221-5237,5242,5245-5254,5259,5261,5264-5265,5269-5272,5279-5282,5291,5298-5310,5312-5318,5320-5321,5339,5343-5344,5347,5349-5364,5370,5377,5397-5437,5440-5445,5450,5453-5458,5461-5465,5470-5475,5490,5500-5507,5510,5520,5530,5540,5544,5550,5552-5557,5560,5565-5569,5573-5575,5579-5586,5597-5605,5611-5612,5618,5620-5622,5627-5639,5646,5665-5667,5670-5684,5687-5689,5693,5696,5700,5705,5711,5713-5730,5732,5734,5737,5741-5748,5750,5755,5757,5766-5771,5777,5780-5787,5793-5794,5800-5804,5806-5808,5810-5815,5817-5818,5820-5827,5831,5834,5836,5838-5842,5845,5848-5850,5852-5854,5858-5860,5862-5863,5868-5869,5871,5874-5875,5877-5878,5881,5883,5887-5888,5899-5915,5917-5918,5920-5927,5931,5934,5936,5938-5940,5945,5948-5950,5952-5954,5958-5963,5966,5968-5969,5971,5974-5975,5977-5979,5981,5984-5993,5997-6077,6080-6088,6090-6091,6099-6118,6120-6124,6126,6129-6130,6133,6140-6149,6156,6159-6163,6200-6201,6203,6209,6222,6241-6244,6247,6250-6253,6259,6267-6269,6273-6274,6300-6301,6306,6309-6310,6315-6317,6320-6326,6343-6344,6346-6347,6349-6350,6355,6360,6363,6370,6379,6382,6389-6390,6400-6410,6412,6417-6421,6432,6442-6446,6455-6456,6464,6471,6480-6489,6500-6511,6513-6515,6520,6535,6543-6544,6547-6551,6558,6565-6568,6579-6583,6588,6600-6602,6606,6619-6629,6632-6636,6640,6644,6646-6647,6650,6653,6655-6657,6662,6665-6673,6678-6679,6687-6690,6692,6696-6697,6699-6703,6709-6711,6714-6716,6725,6732,6734,6767-6771,6777-6780,6784-6792,6801,6817,6831,6839,6841-6842,6850,6868,6877,6881,6888,6896-6897,6900-6901,6920,6922,6935-6936,6942,6946,6951,6956,6961-6966,6969-6970,6972-6973,6997-7026,7030-7031,7033,7040,7043,7050-7051,7067-7068,7070-7073,7080,7088,7092,7095,7099-7104,7106-7107,7117,7119,7121,7123,7128-7129,7161-7174,7181,7184,7200-7202,7215-7216,7218,7227-7229,7231,7235-7237,7241,7244,7262,7272-7283,7300-7359,7365,7391-7395,7397,7400-7402,7410-7411,7420-7421,7426-7431,7435,7437-7438,7443,7451,7456,7464,7471,7473-7474,7478,7491,7496,7500-7501,7508-7512,7542-7551,7553,7555,7560,7563,7566,7569-7570,7574,7588,7597,7600,7606,7624-7631,7633-7634,7637,7648,7654,7663,7672-7677,7680,7683,7685,7687-7689,7697,7700-7701,7707-7708,7720,7724-7728,7734,7738,7741-7744,7747,7749,7770-7772,7775,7777-7781,7784,7786-7789,7794,7797-7802,7810,7813,7830,7845-7847,7852-7854,7869-7872,7878,7880,7887,7895,7900-7903,7911,7913,7920-7921,7929,7932-7933,7937-7938,7962,7967,7975,7979-7982,7997-8011,8014-8016,8018-8023,8025-8026,8029,8031-8034,8037,8040-8045,8050-8060,8064,8066-8067,8070,8074,8076-8077,8080-8093,8095,8097-8102,8110,8115-8118,8121-8123,8128-8133,8140,8144,8148-8149,8153,8160-8162,8180-8184,8189-8195,8199-8202,8204-8208,8211,8222,8230-8232,8243,8245,8248,8254-8255,8266,8268,8270,8273,8276,8280,8282,8290-8295,8300-8301,8308,8313,8320-8322,8333,8339,8351,8376-8380,8383-8385,8400-8405,8409,8415-8417,8423,8442-8445,8450-8455,8457,8470-8474,8477,8479,8481,8484,8500-8503,8515,8530-8531,8539-8540,8554-8555,8562,8567,8600-8601,8609-8615,8621,8640,8644,8648-8649,8651-8652,8654-8655,8658,8665-8666,8673,8675-8676,8680,8686,8688,8699,8701,8711,8732-8733,8736,8750,8752,8756,8763-8766,8770,8772,8778,8786-8787,8790,8793,8798,8800-8801,8804-8805,8807-8809,8834,8843,8865,8873,8877-8883,8887-8894,8898-8901,8910-8913,8925,8937,8953-8954,8980-8981,8987,8989-8991,8994,8996-9005,9007-9011,9013,9020-9026,9037,9040,9044,9050-9051,9060-9061,9065,9071,9080-9081,9083-9093,9098-9107,9110-9111,9119,9122-9123,9125,9128,9130-9131,9133,9152,9160-9164,9170,9183,9191,9197-9198,9200-9217,9220,9222,9255,9277-9287,9290,9292-9295,9300,9306,9312,9318,9321,9333,9339,9343-9346,9351,9364,9374,9380,9387-9390,9396-9397,9400-9402,9409,9415,9418,9443-9445,9450,9454,9464,9478,9485,9493,9500-9503,9513,9522,9527,9535-9536,9555,9575,9583,9592-9600,9612-9614,9616-9621,9628-9632,9640,9643,9648,9654,9661,9665-9668,9673-9674,9679-9680,9683,9694-9695,9700,9745,9747,9750,9753,9762,9777,9800-9802,9812,9814-9815,9823,9825-9826,9830,9844,9875-9878,9888-9889,9898-9901,9903,9908-9912,9914-9915,9917,9919,9925,9929,9941,9943-9944,9950-9956,9966,9968,9971,9975,9978-9979,9981,9987-9988,9990-10012,10018-10020,10022-10025,10034-10035,10042,10045,10050-10051,10055,10058,10064,10080-10083,10093,10100-10104,10107,10110-10111,10113-10117,10125,10128-10129,10160-10162,10180,10200-10201,10215,10238,10243,10245-10246,10252-10253,10255,10260-10261,10280,10288,10321,10338,10347,10357,10387,10414,10439,10443,10494,10500,10509,10529,10535,10540-10544,10548,10550-10556,10565-10567,10601-10602,10616-10617,10621,10626,10628-10629,10631,10699,10754,10778,10800,10805,10809-10810,10842,10852,10860,10873,10878,10880,10900,10933,10990,11000-11001,11003,11007,11019,11026,11031-11033,11089,11095,11100,11103-11106,11108-11112,11161-11165,11171-11175,11180,11200-11202,11208,11211,11224,11250,11288,11296,11319-11321,11367,11371,11401,11430,11489,11552,11600,11623,11697,11720,11723,11735,11751,11796,11813,11862-11863,11876-11877,11940,11967,11971,12000-12010,12012-12013,12019,12021,12031,12034,12059,12077,12080,12090,12096-12097,12109,12121,12132,12137,12146,12156,12168,12171-12172,12174,12192,12215,12225,12240,12243,12251,12262,12265,12271,12275,12296,12300,12302,12321-12322,12340,12345-12346,12380,12414,12452,12699,12702,12753,12766,12865,12891-12892,12955,12962,13017,13093,13130,13132,13140,13142,13149,13160,13167,13188,13192-13194,13216-13218,13223-13224,13229,13250,13261,13264-13265,13306,13318,13340,13359,13400,13456,13502,13580,13695,13701-13702,13705-13706,13708-13718,13720-13724,13730,13766,13782-13786,13818-13823,13846,13882,13894,13899,13929-13930,14000-14002,14033-14034,14141-14143,14145,14147,14149-14150,14154,14218,14237-14238,14250,14254,14414,14418,14441-14444,14500,14534,14545,14693,14733,14827,14891,14916,14936-14937,15000-15005,15050,15118,15126,15145,15151,15190-15191,15275,15317,15344-15345,15363,15402,15448,15550,15555,15631,15645-15646,15660,15670,15677,15722,15730,15740,15742,15758,15915,15998-16003,16012,16016,16018,16020-16021,16048,16080,16113,16161-16162,16270,16273,16283,16286,16297,16309-16311,16349,16360-16361,16367-16368,16372,16384-16385,16444,16464,16619,16665-16666,16705,16723-16725,16789,16797,16800,16845,16851,16900-16901,16950,16959,16991-16995,17007,17016-17017,17070,17089,17129,17184-17185,17219-17225,17234-17235,17251,17255,17300,17409,17413,17500,17555,17595,17700-17702,17715,17729,17754-17756,17777,17801-17802,17860,17867,17877,17969,17985,17988,17997,18000,18012,18015,18018,18040,18080,18101,18104,18136,18148,18181-18187,18231,18241-18243,18262,18264,18333,18336-18337,18380,18439,18463,18505,18517,18569,18634-18635,18668-18669,18769,18874,18881,18887-18888,18910,18962,18988,19000,19007,19010,19020,19101,19130,19150,19191,19194,19200-19201,19220,19283,19315,19333,19350,19353,19398,19403,19410-19412,19464,19501,19539-19541,19612,19634,19715,19780,19788,19801,19842,19852,19900,19995-19996,19998-20003,20005,20011-20014,20017,20021,20031-20032,20034,20039,20046,20048-20049,20052,20057,20076,20080,20085,20089,20102,20106,20111,20118,20125,20127,20147,20167,20179-20180,20202,20221-20228,20280,20473,20480,20670,20734,20828,20883,20934,20940,20990,20999-21000,21010-21011,21078,21201,21212,21221,21473,21553-21554,21571,21590,21631,21634,21728,21792,21800,21845-21849,21891,21915,22000-22005,22022,22063,22100,22125,22128,22177,22200,22222-22223,22273,22289-22290,22305,22321,22335,22341,22343,22347,22350-22351,22370,22537,22555,22563,22711,22719,22727,22763,22769,22800,22882,22939,22951,22959,22969,23000-23005,23017,23040,23052-23053,23219,23228,23270,23272,23294,23296,23333,23342,23382,23400-23402,23430,23451,23456-23457,23502,23546,23723,23796,23887,23953,24000-24006,24218,24242,24249,24321-24323,24386,24392,24416,24444,24465,24552,24554,24577,24616,24666,24676-24678,24680,24754,24800,24850,24922,24999-25009,25174,25260,25262,25288,25327,25445,25471,25473,25486,25565,25576,25604,25703,25717,25734-25735,25793,25847,25900-25903,25954-25955,26000-26001,26007,26133,26208,26214,26257,26260-26263,26340,26417,26470,26486-26487,26489,26669,26972,27000-27010,27015-27019,27055,27074-27075,27087,27204,27316,27345,27350-27353,27355-27357,27372,27374,27442,27504,27521,27537,27665,27715,27770,27782,27876,27999-28001,28017,28114,28119,28142,28200-28201,28211,28240,28374,28567,28589,28717,28850-28851,28924,28967,29045,29152,29167,29243,29507,29672,29810,29831,29999-30005,30087,30100,30195,30260,30299,30400,30519,30599,30644,30659,30704-30705,30718,30832,30896,30951,30999,31016,31020,31029,31033,31038,31058,31072,31337,31339,31386,31400,31416,31438,31457,31522,31620,31657,31685,31727-31728,31765,31948-31949,32006,32022,32031,32034,32088,32102,32200,32219,32249,32260-32261,32400,32483,32635-32636,32764-32765,32767-32792,32797-32799,32801,32803,32807,32811,32814-32816,32820,32822,32835,32837,32842,32858,32868-32869,32871,32888,32896-32898,32904-32905,32908,32910-32911,32932,32944,32960-32961,32976,33000,33011,33017,33060,33070,33087,33123-33124,33175,33192,33200,33203,33277,33327,33331,33333-33335,33337,33354,33367,33395,33434-33435,33444,33453,33522-33523,33550,33554,33604-33605,33656,33841,33879,33882,33889,33895,33899,34021,34036,34096,34189,34249,34317,34341,34378-34379,34381,34401,34507,34510,34567,34571-34573,34683,34728,34765,34783,34833,34875,34962-34964,34980,35000-35006,35033,35050,35100,35116,35131,35217,35272,35349,35354-35357,35392-35393,35401,35500,35506,35513,35553,35593,35731,35879,35900-35901,35906,35929,35986,36001,36046,36104-36105,36256,36275,36368,36411,36423-36424,36436,36443-36444,36462,36508,36524,36530,36552,36602,36659,36677,36694,36700,36710,36748,36823-36824,36865,36914,36950,36962,36983,37121,37151,37174,37185,37218,37393,37475,37483,37522,37601,37607,37614,37647,37654,37674,37777,37789,37839,37855,38000-38002,38029,38037,38185,38188,38194,38201-38203,38205,38224,38270,38292,38313,38331,38358,38412,38422,38446,38462,38472,38481,38546,38561,38570,38761,38764,38780,38800,38805,38865,38936,39067,39117,39136,39265,39293,39376,39380,39433,39482,39489,39630,39659,39681,39732,39763,39774,39795,39869,39883,39895,39917,40000-40003,40005,40011,40023,40193,40306,40393,40400,40404,40457,40489,40513,40614,40628,40712,40732,40754,40811-40812,40834,40841-40843,40853,40911,40951,41064,41111,41121,41123,41142,41230,41250,41281,41318,41342,41345,41348,41398,41442,41511,41523,41551,41632,41773,41794-41797,41808,42001,42035,42127,42158,42251,42276,42322,42449,42452,42508-42510,42559-42560,42575,42590,42632,42675,42679,42685,42735,42906,42990,43000,43002,43018,43027,43103,43139,43143,43188-43191,43210,43212,43231,43242,43425,43438-43441,43654,43690,43734,43823,43868,44004,44101,44119,44123,44176,44200,44321-44323,44334,44380,44410,44431,44442-44444,44479,44501,44505,44541,44544,44553,44600,44616,44628,44704,44709,44711,44818,44900,44965,44981,45000-45002,45038,45045,45050,45054,45100,45136,45164,45220,45226,45413,45438,45463,45514,45602,45624,45678,45697,45777,45824-45825,45864,45960,45966,46034,46069,46115,46171,46182,46200,46310,46336,46372,46418,46436,46593,46813,46992,46996,46998-47001,47012,47029,47100,47119,47197,47267,47348,47372,47448,47544,47557,47567,47581,47595,47624,47634,47700,47777,47806,47808-47809,47850,47858,47860,47966,47969,48000-48005,48009,48048-48050,48067,48080,48083,48127-48129,48153,48167,48356,48434,48556,48619,48631,48648,48653,48682,48783,48813,48925,48966-48967,48973,49000-49002,49048,49132,49150,49152-49161,49163-49173,49175-49176,49179,49186,49189-49191,49195-49197,49201-49204,49211,49213,49216,49228,49232,49235-49236,49241,49275,49302,49352,49372,49398,49400-49401,49452,49498,49500,49519-49522,49597,49603,49678,49751,49762,49765,49803,49927,49999-50003,50006,50016,50019,50040,50050,50101,50189,50198,50202,50205,50224,50246,50258,50277,50300,50356,50389,50500,50513,50529,50545,50576-50577,50585,50636,50692,50733,50787,50800,50809,50815,50831,50833-50836,50849,50854,50887,50903,50945,50997,51011,51020,51037,51067,51103,51118,51139,51191,51233-51235,51240,51300,51343,51351,51366,51413,51423,51460,51484-51485,51488,51493,51515,51582,51658,51771-51772,51800,51809,51906,51909,51961,51965,52000-52003,52025,52046,52071,52173,52225-52226,52230,52237,52262,52391,52477,52506,52573,52660,52665,52673,52675,52710,52735,52822,52847-52851,52853,52869,52893,52948,53085,53178,53189,53211-53212,53240,53313-53314,53319,53361,53370,53460,53469,53491,53535,53633,53639,53656,53690,53742,53782,53827,53852,53910,53958,54045,54075,54101,54127,54235,54263,54276,54320-54321,54323,54328,54514,54551,54605,54658,54688,54722,54741,54873,54907,54987,54991,55000,55020,55055-55056,55183,55187,55227,55312,55350,55382,55400,55426,55479,55527,55555-55556,55568-55569,55576,55579,55600,55635,55652,55684,55721,55758,55773,55781,55901,55907,55910,55948,56016,56055,56259,56293,56507,56535,56591,56668,56681,56723,56725,56737-56738,56810,56822,56827,56973,56975,57020,57103,57123,57294,57325,57335,57347,57350,57352,57387,57398,57479,57576,57665,57678,57681,57702,57730,57733,57797,57891,57896,57923,57928,57988,57999,58001-58002,58072,58080,58107,58109,58164,58252,58305,58310,58374,58430,58446,58456,58468,58498,58562,58570,58610,58622,58630,58632,58634,58699,58721,58838,58908,58970,58991,59087,59107,59110,59122,59149,59160,59191,59200-59202,59239,59340,59499,59504,59509-59510,59525,59565,59684,59778,59810,59829,59841,59987,60000,60002-60003,60020,60055,60086,60111,60123,60146,60177,60227,60243,60279,60377,60401,60403,60443,60485,60492,60504,60544,60579,60612,60621,60628,60642,60713,60728,60743,60753,60782-60783,60789,60794,60989,61159,61169-61170,61402,61439-61441,61473,61516,61532,61613,61616-61617,61669,61722,61734,61827,61851,61900,61942,62006,62042,62078,62080,62188,62312,62519,62570,62674,62866,63105,63156,63331,63423,63675,63803,64080,64127,64320,64438,64507,64551,64623,64680,64726-64727,64890,65000,65048,65129,65301,65310-65311,65389,65488,65514" } # 处理请求的端口数与本地设定的断口数的转换 class Port: # 系统配置的top_ports可选数量列表 top_arr = [] def __init__(self): for item in data: if item.startswith('TOP_') and item.endswith('_PORTS'): self.top_arr.append(int(item.split('_')[1])) self.top_arr = sorted(self.top_arr) self.ports = set() def find_closest_ports(self, k: int, x: int): n = len(self.top_arr) l, r = 0, n - k while l < r: m = (l + r) // 2 if x - self.top_arr[m] > self.top_arr[m + k] - x: l = m + 1 else: r = m return self.top_arr[l:l + k] def convert(self, port_count: int): res = self.find_closest_ports(1, port_count)[0] attr = data['TOP_{}_PORTS'.format(res)] return attr def add_top_ports(self, port_count: int): self.add_ports(self.convert(port_count)) def add_ports(self, ports): ports = self.rectify(ports) p_list = str(ports).split(',') for p in p_list: try: p = int(p) self.ports.add(p) except: try: p_range = p.split('-') st = int(p_range[0]) ed = int(p_range[1]) while st < ed + 1: self.ports.add(st) st += 1 except ValueError: logger.warning('捕捉到错误端口{}'.format(p)) continue def discard_ports(self, ports): ports = self.rectify(ports) p_list = str(ports).split(',') if not self.ports: self.add_ports('1-65535') for p in p_list: try: p = int(p) self.ports.remove(p) except ValueError: p_range = p.split('-') try: st = int(p_range[0]) ed = int(p_range[1]) while st < ed + 1: try: self.ports.remove(st) st += 1 except KeyError: st += 1 except ValueError: pass except KeyError: pass def get_ports(self): l = list(self.ports) if l: return self.l2s(l) else: return '1-65535' def get_list_ports(self): return list(self.ports) @staticmethod def rectify(string: str): string = string.replace(',', ',').replace(' ', '') return string @staticmethod def l2s(port_list: list): """ 端口list转字符串,list中的端口是int型 :param port_list: :return: """ port_list = sorted(port_list) port_iter = iter(port_list) # cnt,用来记录连续端口的count cnt = 0 port = port_iter.__next__() # last,用来存储上一个未存的端口,结合cnt就是一批未存的端口 last = port result = [] while True: try: port = port_iter.__next__() if last + cnt + 1 == port: cnt += 1 elif last + 1 != port: result.append(str(last)) if not cnt else result.append(str(last) + '-' + str(last + cnt)) cnt = 0 last = port except StopIteration: # 做最后的处理 result.append(str(last)) if not cnt else result.append(str(last) + '-' + str(last + cnt)) break return ','.join(result) @staticmethod def split_str_ports(ports: str): """ 1,3-5 → 1,3,4,5 :return: """ ports = ports.split(',') return Port.split_list_ports(ports) @staticmethod def split_list_ports(ports: list): """ [1,3-5] → 1,3,4,5 :return: """ port_iter = iter(ports) # last,用来存储上一个未存的端口,结合cnt就是一批未存的端口 p_set = set() res = '' while True: try: port = port_iter.__next__() try: port = int(port) p_set.add(str(port)) except: p_range = port.split('-') st = int(p_range[0]) ed = int(p_range[1]) while st < ed + 1: try: p_set.add(str(st)) st += 1 except KeyError: st += 1 except StopIteration: # 做最后的处理 res = list(p_set) break return ','.join(res) @staticmethod def split(port_str): """ 将端口拆分成不超过8155个字符的多个端口列表 :param port_str: :return: 注:暂时用不上 """ port_list = port_str.split(',') port_target = [] s = '' i = 0 n = len(port_list) while i < n: s += port_list[i] + ',' if len(s) > 8155 or i == (n - 1): s = s[:-1] port_target.append(s) s = '' i += 1 return port_target @staticmethod def split_port(ports: str, group_limit=13107) -> list: """ 切割端口为多个分组,可用于masscan同时扫描多个ip时,端口分组扫描(会大大提升扫描准确率) :param ports: 字符串形式的port目标 :param group_limit: 每组的最大端口数,一般来说分5组,所以默认是65535/5 = 13107 :return: 分组好的多个字符串形式port列表 """ def ave_list(target: list, n): for i in range(0, len(target), n): yield target[i:i + n] res = [] pc = Port() pc.add_ports(ports) pl = len(pc.ports) piece = math.ceil(pl / group_limit) if piece <= 2: # DO NOTHING res.append(ports) else: temp = ave_list(list(pc.ports), math.ceil(pl / piece)) for item in temp: res.append(Port.l2s(item)) return res
yuan-tool
/yuan-tool-2.57.tar.gz/yuan-tool-2.57/yuantool/network/port.py
port.py
# Yuanfen Python Library ## build && upload ```bash $ python3 setup.py sdist bdist_wheel $ python3 -m twine upload dist/* ``` ## utils.config Support .json, .yaml, .ini files. Support auto reloading while config file changes. ```python config_json = Config(os.path.abspath("config.json")) config_yaml = Config(os.path.abspath("config.yaml")) config_ini = Config(os.path.abspath("config.ini")) print(config_ini["app"]["config_a"]) print(config_yaml["movie"]["name"]) ``` ## utils.logger Stream and TimedRotatingFile handlers for logging. ```python logger.set_level(level) logger.debug("debug log") logger.info("debug log") logger.warn("debug log") logger.error("debug log") ```
yuanfen
/yuanfen-2023.5.17.1.tar.gz/yuanfen-2023.5.17.1/README.md
README.md
# yuanian [![image](https://img.shields.io/badge/Pypi-0.0.1-green.svg)](https://pypi.org/project/yuanian) [![image](https://img.shields.io/badge/python-3.6+-blue.svg)](https://www.python.org/) [![image](https://img.shields.io/badge/license-GNU_GPL--V3-blue.svg)](LICENSE) [![image](https://img.shields.io/badge/author-kunyuan-orange.svg?style=flat-square&logo=appveyor)](https://github.com/beidongjiedeguang) ## Requirements ```python sparrow_tool ``` ----------------------------------------- ## Document TODO ## Installation ```bash pip install yuanian ``` ## Synopsis TODO ## Usage TODO
yuanian
/yuanian-0.0.1.tar.gz/yuanian-0.0.1/README.md
README.md
from .config import * from .tiledmap import TiledMap class EasySpriteStrategy(): ''' 这是一个动画精灵类 输入:一张图片名称 方法:调用update方法来输出图片 ''' def __init__(self, img): if isinstance(img, str): self._image = pygame.image.load(img).convert_alpha() else: self._image = img def __len__(self): return 1 def __getitem__(self, frame): raise NotImplementedError def __setitem__(self, frame): raise NotImplementedError def update(self): return self._image class TiledMapStrategy(): def __init__(self, tiledmap): self.tm = tiledmap.make_map().convert_alpha() def update(self): return self.tm class ListSpriteStrategy(): ''' 这是一个动画精灵类 输入:以列表形式存储的图片名称 方法:调用update方法来输出图片 ''' def __init__(self, imgs): self._frame = 0 self._images = [] self.playing = False self.dt = 0.05 self._last_update_time = 0 for img in imgs: if isinstance(img, str): self._images.append(pygame.image.load(img).convert_alpha()) else: self._images.append(img) def __repr__(self): return f"sprites = {self._images}, frame = {self._frame}" def __len__(self): return len(self._images) def __getitem__(self, frame): assert frame < len(self._images), 'IndexError' return self.images[frame] def __setitem__(self): raise NotImplementedError @ property def frame(self): return self._frame @ frame.setter def frame(self, frame): self._frame = frame % len(self._images) def set_dt(self, dt): self.dt = dt def update(self): image = self._images[self._frame] if self.playing and time.time() - self._last_update_time > self.dt: self._last_update_time = time.time() self._frame += 1 if self._frame == len(self._images): self._frame = 0 return image class AnimatorStrategy(): ''' 这是一个动画精灵类 输入:以字典形式存储的图片名称 方法:调用update方法来输出图片 ''' def __init__(self, imgs_dict): self._frame = 0 self._imgs_dict = {} self.playing = False self._last_update_time = 0 self._state = 0 for state in imgs_dict: self._imgs_dict[state] = {'animation':[], 'dt':0.05, 'next_state':state, 'start_func':None, 'end_func':None} for img in imgs_dict[state]: if isinstance(img, str): self._imgs_dict[state]['animation'].append(pygame.image.load(img).convert_alpha()) else: self._imgs_dict[state]['animation'].append(img) self._state = state self._prestate = self._state self._state_temp = self._state def __repr__(self): return f"sprites = {self._imgs_dict}, frame = {self._frame}, state = {self._state}" def __len__(self): raise NotImplementedError def __getitem__(self, frame): raise NotImplementedError @ property def frame(self): return self._frame @ frame.setter def frame(self, frame): self._frame = frame % len(self._imgs_dict[self.state]['animation']) @property def state(self): return self._state @state.setter def state(self, state): if state not in self._imgs_dict: raise KeyError self._state_temp = state def set_dt(self, state, dt): if state: self._imgs_dict[state]['dt'] = dt else: for state in self._imgs_dict: self._imgs_dict[state]['dt'] = dt def set_next_state(self, state, next_state): self._imgs_dict[state]['next_state'] = next_state def set_start_func(self, state, func): self._imgs_dict[state]['start_func'] = func def set_end_func(self, state, func): self._imgs_dict[state]['end_func'] = func def update(self): self._prestate = self._state self._state = self._state_temp if self._state != self._prestate: self._frame = 0 image = self._imgs_dict[self._state]['animation'][self._frame] if self.playing and time.time() - self._last_update_time > self._imgs_dict[self._state]['dt']: self._last_update_time = time.time() self._frame += 1 if self._frame == len(self._imgs_dict[self._state]['animation']): if self._imgs_dict[self.state]['end_func']: self._imgs_dict[self.state]['end_func']() self.state = self._imgs_dict[self._state]['next_state'] if self._imgs_dict[self.state]['start_func']: self._imgs_dict[self.state]['start_func']() self._frame = 0 return image class SpriteSheet(): def __init__(self, sheet, w, h): self.sheet = pygame.image.load(sheet).convert_alpha() self.imgs = [] width, height = self.sheet.get_size() tile_width = width // w tile_height = height // h for i in range(h): for j in range(w): self.imgs.append(self.sheet.subsurface(pygame.Rect(j*tile_width, i*tile_height, tile_width, tile_height))) def __getitem__(self, key): return self.imgs[key] def __repr__(self): return self.imgs class Sprite(pygame.sprite.DirtySprite): ''' Only allow one image ''' autos = {pygame.Surface:EasySpriteStrategy, str:EasySpriteStrategy, TiledMap:TiledMapStrategy, list:ListSpriteStrategy, dict:AnimatorStrategy, SpriteSheet:ListSpriteStrategy} def __init__(self, imgs): pygame.sprite.DirtySprite.__init__(self, global_var.ALL_SPRITES) self.dirty = 2 self._offset = vec(0, 0) self._is_flip_h = False self._is_flip_v = False sprite_strategy = Sprite.autos[type(imgs)] self._sprite_strategy = sprite_strategy(imgs) self._red = 255 self._green = 255 self._blue = 255 self._alpha = 255 self._visible = True self.rect = self._sprite_strategy.update().get_rect() # Flags to inform the class whether to perform the transformation self.fliped = False self.scaled = False self.rotated = False self.modified = False def set_parent(self, parent): self._parent = parent @property def sprite_strategy(self): return self._sprite_strategy @property def is_flip_h(self): return self._is_flip_h @is_flip_h.setter def is_flip_h(self, h): self._is_flip_h = h @property def is_flip_v(self): return self._is_flip_v @is_flip_v.setter def is_flip_v(self, v): self._is_flip_v = v @property def red(self): return self._red @red.setter def red(self, r): self._red = r @property def green(self): return self._green @green.setter def green(self, g): self._green = g @property def blue(self): return self._blue @blue.setter def blue(self, b): self._blue = b @property def alpha(self): return self._alpha @alpha.setter def alpha(self, a): self._alpha = a @property def visible(self): return self._visible @visible.setter def visible(self, v): self._visible = v @property def width(self): return self.rect.size[0] @property def height(self): return self.rect.size[1] def update(self): self.image = self._sprite_strategy.update().copy() # 翻转 if self.fliped: self.image = pygame.transform.flip(self.image, self._is_flip_h, self._is_flip_v) # 放缩 if self.scaled: width, height = self.image.get_rect().size self.image = pygame.transform.scale(self.image, (int(self._parent.scl[0]*width), int(self._parent.scl[1]*height))) # 旋转 if self.rotated: self.image = pygame.transform.rotate(self.image, self._parent.rot) if self.modified: if self._visible: self.image.fill((self._red, self._green, self._blue, self._alpha), None, pygame.BLEND_RGBA_MULT) else: self.image.fill((self._red, self._green, self._blue, 0), None, pygame.BLEND_RGBA_MULT) self.rect = self.image.get_rect() camera_offset = vec(global_var.SCREEN.size) - vec(global_var.CAMERA.size) self.rect.center = Cartesian2pygame(self._parent.pos) - camera_offset//2 # 转化为笛卡尔坐标系
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/sprite.py
sprite.py
from .config import * class DialogBox(pygame.sprite.DirtySprite): def __init__(self, parent): pygame.sprite.DirtySprite.__init__(self, global_var.ALL_SPRITES) self.dirty = 2 self.orig_image = pygame.image.load(cwd+'\static\DialogBox.png') self.font = pygame.font.Font(cwd+'\static\simkai.ttf', 25) self._text = '' self._parent = parent self.hide() def say(self, text = None): if text: self._text = str(text) else: self.hide() def show(self): self._visible = True def hide(self): self._visible = False def update(self): self.image = self.orig_image.copy() if self._parent.pos[0] > 0: flipx = True else: flipx = False if flipx: self.image = pygame.transform.flip(self.image, flipx, 0) lines = len(self._text)//12+1 self.image = pygame.transform.scale(self.image, (int(self.image.get_width() * 0.6), int(self.image.get_height() * lines / 10 + 50))) for i in range(lines): text = self.font.render(f"{self._text[i*12:(i+1)*12]}", 1, (0, 0, 0), (255, 255, 255)) self.image.blit(text, (int(10*lines/5)+30,20+int(40*lines/5) + i * 30)) if not self._visible: self.image.fill((255, 255, 255, 0), None, pygame.BLEND_RGBA_MULT) self.rect = self.image.get_rect() camera_offset = vec(global_var.SCREEN.size) - vec(global_var.CAMERA.size) if not flipx: if self._parent._gameObject.sprite: self.rect.center = Cartesian2pygame(self._parent.pos) - camera_offset//2 \ + 0.5 * vec(self._parent._gameObject.sprite.width, -self._parent._gameObject.sprite.height)+vec(30,-50) else: self.rect.center = Cartesian2pygame(self._parent.pos) - camera_offset//2 +vec(30,-50) else: if self._parent._gameObject.sprite: self.rect.center = Cartesian2pygame(self._parent.pos) - camera_offset//2 \ - 0.5 * vec(self._parent._gameObject.sprite.width, self._parent._gameObject.sprite.height) +vec(-30,-50) else: self.rect.center = Cartesian2pygame(self._parent.pos) - camera_offset//2 +vec(-30,-50) global_var.ALL_SPRITES.move_to_front(self) class TextBox(pygame.sprite.DirtySprite): def __init__(self, size = 20, font = cwd+'\static\simkai.ttf'): pygame.sprite.DirtySprite.__init__(self, global_var.ALL_SPRITES) self.font = pygame.font.Font(font, size) self._text = '' self._pos = vec(0, 0) self._color = (0, 0, 0) def print(self, text = None): self._text = str(text) def goto(self, x, *y): if y: self.pos = (x, *y) else: self.pos = x @ property def pos(self): return self._pos @ pos.setter def pos(self, pos): self._pos = pos @ property def color(self): return self._color @ color.setter def color(self, color): self._color = color def update(self): self.image = self.font.render(f"{self._text}", 2, self._color) self.rect = self.image.get_rect() self.rect.center = Cartesian2pygame(self._pos) global_var.ALL_SPRITES.move_to_front(self)
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/textbox.py
textbox.py
from .config import * class GameObject(): def __init__(self): self._sprite = None self._body = None self._tiledmap_bodies = None self._pos = vec(0, 0) self._rot = 0 self._scl = vec(1, 1) self.alive = True def __repr__(self): return f"Sprite;Physics" def set_sprite(self, sprite): self._sprite = sprite self._sprite.set_parent(self) def set_body(self, body): self._body = body if self._body: self._body.set_parent(self) def set_tiledmap_bodies(self, tiledmap_bodies): self._tiledmap_bodies = tiledmap_bodies if self._tiledmap_bodies: self._tiledmap_bodies.set_parent(self) @property def sprite(self): return self._sprite @property def body(self): return self._body @ property def tiledmap_bodies(self): return self._tiledmap_bodies @ property def pos(self): return self._pos @ pos.setter def pos(self, pos): if self._sprite: self._pos = vec(pos) if self._body: self._body.set_pos(pos) if self._tiledmap_bodies: self._tiledmap_bodies.set_pos(pos) @ property def x(self): return self._pos[0] @ property def y(self): return self._pos[1] @ x.setter def x(self, x): pos = vec(x, self._pos[1]) self.pos = pos @ y.setter def y(self, y): pos = vec(self._pos[0], y) self.pos = pos @ property def rot(self): return self._rot @ rot.setter def rot(self, rot): if self.sprite: self.sprite.rotated = True self._rot = rot @ property def scl(self): return self._scl @ scl.setter def scl(self, xscl, *yscl): if yscl: self._scl = vec(xscl, *yscl) else: self._scl = vec(xscl) def kill(self): if self._sprite: self._sprite.kill() self._sprite if self._body: self._body.kill() if self._tiledmap_bodies: self._tiledmap_bodies.kill() self._sprite = None self._body = None self._tiledmap_bodies = None self.alive = False
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/game_object.py
game_object.py
from .game_object import * from .screen import * from .sprite import * from .physics import * from .events import * from .tiledmap import TiledMap from .textbox import * from .music import * from .draw import * from .constraints import * import random import time import sys IS_UPDATED = 0 SPEED = 1 def tracer(f): global IS_UPDATED IS_UPDATED = f def speed(s): global SPEED SPEED = s def random_pos(): return (random.randint(- global_var.WIDTH // 2, global_var.WIDTH // 2), random.randint(- global_var.HEIGHT // 2, global_var.HEIGHT // 2)) def debug(): global_var.DEBUG_DRAW = True def set_gravity(x, *y): if y: global_var.SPACE.gravity = (x, *y) else: global_var.SPACE.gravity = x def set_mouse_visible(v): pygame.mouse.set_visible(v) def sign(n): if n > 0: return 1 elif n < 0: return -1 else: return 0 class NewGameObject(): def __init__(self, imgs = None, size = None, body_type = pymunk.Body.KINEMATIC, sensor = False): self._gameObject = GameObject() if imgs: self._gameObject.set_sprite(Sprite(imgs)) if size: if isinstance(size, int): self._gameObject.set_body(Body(body_type, 'CIRCLE', size = size, sensor = sensor)) self.radius = self._gameObject.body.shape.radius elif isinstance(size, tuple): self._gameObject.set_body(Body(body_type, 'BOX', size = size, sensor = sensor)) self.vertices = self._gameObject.body.shape.get_vertices() elif isinstance(size, list): if isinstance(size[0], list): self._gameObject.set_body(Body(body_type, 'POLY', size = size, sensor = sensor)) self.vertices = self._gameObject.body.shape.get_vertices() else: objs = size tiledmap_objects = TiledMapBodies(body_type, objs, sensor) self._gameObject.set_tiledmap_bodies(tiledmap_objects) self._direction = vec(1, 0) self._dialogBox = None self._get_clicked = False global_var.GROUP.add(self) self._just_released = False self.collision_dict = {} self.sounds = [] self.volume = 1 if self._gameObject.sprite: self._gameObject.sprite.update() def __len__(self): raise NotImplementedError def __getitem__(self): raise NotImplementedError def __setitem__(self): raise NotImplementedError def __bool__(self): return True def __del__(self): pass ''' 运动命令 ''' def forward(self, d): n = 0 #d = int(d) speed = min(abs(d), SPEED) while n < abs(d): self._gameObject.pos += self._direction * speed * sign(d) n += speed if IS_UPDATED: update() def backward(self, d): n = 0 #d = int(d) speed = min(abs(d), SPEED) while n < abs(d): self._gameObject.pos -= self._direction * speed * sign(d) n += speed if IS_UPDATED: update() def _rotate(self, rot): self.rotate_image(rot) self.rotate_direction(rot) def rotate_direction(self, rot): self.dir = self.dir.rotate(rot) def rotate_image(self, rot): self.rot += rot @ property def rot(self): return self._gameObject.rot @ rot.setter def rot(self, r): self._gameObject.rot = r if self._gameObject.sprite: self._gameObject.sprite.rotated = True if self._gameObject.body: self._gameObject.body.set_rot(r) if self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.set_rot(r) @ property def dir(self): return self._direction @ dir.setter def dir(self, d): self._direction = d def left(self, a): n = 0 #a = int(a) speed = min(abs(a), SPEED) while n < abs(a): self._rotate(speed * sign(a)) n += speed if IS_UPDATED: update() def right(self, a): n = 0 #a = int(a) speed = min(abs(a), SPEED) while n < abs(a): self._rotate(-speed * sign(a)) n += speed if IS_UPDATED: update() def slide_to(self, pos, v = 1): distance = vec(pos) - self._gameObject.pos if distance.length() < v: self._gameObject.pos = vec(pos) return True self._gameObject.pos += distance.normalize() * v return False def goto(self, x, *y): if y: self._gameObject.pos = vec(x, *y) else: self._gameObject.pos = vec(x) if self._gameObject.body: self._gameObject.body.velocity = vec(0,0) #update() def face_to(self, x, *y, VEC = False): if not VEC: if y: self.rot = - (vec(x, *y) - self._gameObject.pos).angle_to(vec(1, 0)) self.dir = (vec(x, *y) - self._gameObject.pos).normalize() else: self.rot = - (vec(x) - self._gameObject.pos).angle_to(vec(1, 0)) if (vec(x) - self._gameObject.pos).length() != 0: self.dir = (vec(x) - self._gameObject.pos).normalize() else: if y: self.rot = - vec(x, *y).angle_to(vec(1, 0)) self.dir = vec(x, *y).normalize() else: self.rot = - vec(x).angle_to(vec(1, 0)) if vec(x).length() != 0: self.dir = vec(x).normalize() @ property def pos(self): return self._gameObject.pos @ property def dir(self): return self._direction @ property def x(self): return self._gameObject.pos[0] @ property def y(self): return self._gameObject.pos[1] @ pos.setter def pos(self,p): self._gameObject.pos = p if self._gameObject.body: self._gameObject.body.velocity = vec(0,0) if self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.velocity = vec(0,0) @ dir.setter def dir(self, dir): self._direction = dir @ x.setter def x(self, x): if self._gameObject.body: self._gameObject.body.velocity = vec(0,0) if self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.velocity = vec(0,0) self._gameObject.x = x @ y.setter def y(self, y): if self._gameObject.body: self._gameObject.body.velocity = vec(0,0) if self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.velocity = vec(0,0) self._gameObject.y = y @ property def velocity(self): if self._gameObject.body: return self._gameObject.body.velocity elif self._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.velocity @ velocity.setter def velocity(self, v): if self._gameObject.body: self._gameObject.body.velocity = v elif self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.velocity = v @ property def angular_velocity(self): if self._gameObject.body: return self._gameObject.body.angular_velocity elif self._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.angular_velocity @ angular_velocity.setter def angular_velocity(self, v): if self._gameObject.body: self._gameObject.body.angular_velocity = v elif self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.angular_velocity = v ''' 图片命令 ''' def scale(self, scalex, scaley = None): if scaley == None: if self._gameObject.sprite: self._gameObject.sprite.scaled = True self._gameObject.scl = scalex if self._gameObject.body: self.body_scale(scalex, scaley) if self._gameObject.tiledmap_bodies: self.body_scale(scalex, scaley) else: if self._gameObject.sprite: self._gameObject.sprite.scaled = True self._gameObject.scl = (scalex, scaley) if self._gameObject.body: self.body_scale(scalex, scaley) if self._gameObject.tiledmap_bodies: self.body_scale(scalex, scaley) def flipx(self, h): self._gameObject.sprite.fliped = True self._gameObject.sprite.is_flip_h = h def flipy(self, v): self._gameObject.sprite.fliped = True self._gameObject.sprite.is_flip_v = v @ property def red(self): return self._gameObject.sprite.red @ red.setter def red(self, red): self._gameObject.sprite.modified = True self._gameObject.sprite.red = red @ property def green(self): return self._gameObject.sprite.green @ green.setter def green(self, green): self._gameObject.sprite.modified = True self._gameObject.sprite.green = green @ property def blue(self): return self._gameObject.sprite.blue @ blue.setter def blue(self, blue): self._gameObject.sprite.modified = True self._gameObject.sprite.blue = blue @ property def alpha(self): return self._gameObject.sprite.alpha @ alpha.setter def alpha(self, alpha): self._gameObject.sprite.modified = True self._gameObject.sprite.alpha = alpha @ property def color(self): return (self._gameObject.sprite.red, self._gameObject.sprite.green, self._gameObject.sprite.blue, self._gameObject.sprite.alpha) @ color.setter def color(self, color): # 不建议对过大的地图进行此操作,会导致动画变慢 self._gameObject.sprite.modified = True self._gameObject.sprite.red = color[0] self._gameObject.sprite.green = color[1] self._gameObject.sprite.blue = color[2] self._gameObject.sprite.alpha = color[3] def show(self): # 不建议对过大的地图进行此操作,会导致动画变慢 self._gameObject.sprite.modified = True self._gameObject.sprite.visible = True def hide(self): # 不建议对过大的地图进行此操作,会导致动画变慢 self._gameObject.sprite.modified = True self._gameObject.sprite.visible = False @ property def visible(self): return self._gameObject.sprite.visible @ property def width(self): return self._gameObject.sprite.width @ property def height(self): return self._gameObject.sprite.height # 动画命令 @ property def frame(self): return self._gameObject.sprite.sprite_strategy.frame @ frame.setter def frame(self, f): self._gameObject.sprite.sprite_strategy.frame = f def play_anim(self): self._gameObject.sprite.sprite_strategy.playing = True @ property def state(self): return self._gameObject.sprite.sprite_strategy.state @ state.setter def state(self, state): self._gameObject.sprite.sprite_strategy.state = state def set_dt(self, *args): self._gameObject.sprite.sprite_strategy.set_dt(*args) @ property def dt(self): if isinstance(self._gameObject.sprite.sprite_strategy, ListSpriteStrategy): return self._gameObject.sprite.sprite_strategy.dt else: raise NotImplementedError @ dt.setter def dt(self, dt): if isinstance(self._gameObject.sprite.sprite_strategy, ListSpriteStrategy): self.set_dt(dt) else: raise NotImplementedError def set_next_state(self, state, next_state): self._gameObject.sprite.sprite_strategy.set_next_state(state, next_state) def set_start_func(self, state, func): self._gameObject.sprite.sprite_strategy.set_start_func(state, func) def set_end_func(self, state, func): self._gameObject.sprite.sprite_strategy.set_end_func(state, func) # 图层 @ property def layer(self): return global_var.ALL_SPRITES.get_layer_of_sprite(self._gameObject.sprite) @ layer.setter def layer(self, layer): global_var.ALL_SPRITES.change_layer(self._gameObject.sprite, layer) def move_to_front(self): global_var.ALL_SPRITES.move_to_front(self._gameObject.sprite) def move_to_back(self): global_var.ALL_SPRITES.move_to_back(self._gameObject.sprite) # 音效 def play_snd(self, snd = None, volume=None): if snd: s = pygame.mixer.Sound(snd) if not volume: volume = self.volume s.set_volume(volume) if len(self.sounds) == 20: pre_s = self.sounds.pop(0) pre_s.stop() s.play() def set_volume(self, volume): self.volume = volume # 交互 def get_mouse_clicked(self): # 检测鼠标左键是否在按下的状态下 for event in global_var.EVENTS: if event and event.type == MOUSEBUTTONDOWN and self.get_mouse_upon(): self._get_clicked = True self.get_mouse_just_released() if self._get_clicked: return True else: return False def get_mouse_just_clicked(self): # 检测鼠标是否刚刚被按下 for event in global_var.EVENTS: if event and event.type == MOUSEBUTTONDOWN and self.get_mouse_upon(): self._get_clicked = True return True else: return False def get_mouse_just_released(self): # 检测鼠标是否刚刚被松开 if self._just_released: return True self.get_mouse_just_clicked() if self._get_clicked: for event in global_var.EVENTS: if event and event.type == MOUSEBUTTONUP: self._get_clicked = False self._just_released = True if self._get_clicked: return False else: return True else: return False def get_mouse_upon(self): # 检测鼠标是否在图片上 if self.collide(get_mouse_pos()): return True else: return False # 其他 def collide(self, other): if self._gameObject.sprite and self._gameObject.sprite.visible: if isinstance(other, tuple) or isinstance(other, vec): if self._gameObject.body: return self._gameObject.body.point_query(other) elif self._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.point_query(other) else: mask = pygame.mask.from_surface(self._gameObject.sprite.image) offset = self._gameObject.pos - other \ + vec(self._gameObject.sprite.width//2, self._gameObject.sprite.height//2) try: return bool(mask.get_at([int(i) for i in offset])) except: return False else: if self._gameObject.body: if other._gameObject.body: return self._gameObject.body.collide(other._gameObject.body) elif other._gameObject.tiledmap_bodies: return other._gameObject.tiledmap_bodies.collide(self._gameObject.body) elif self._gameObject.tiledmap_bodies: if other._gameObject.body: return self._gameObject.tiledmap_bodies.collide(other._gameObject.body) elif other._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.collide(other._gameObject.tiledmap_bodies) else: mask1 = pygame.mask.from_surface(self._gameObject.sprite.image) mask2 = pygame.mask.from_surface(other._gameObject.sprite.image) offset = self._gameObject.pos - other._gameObject.pos \ + vec(self._gameObject.sprite.width//2, self._gameObject.sprite.height//2)\ - vec(other._gameObject.sprite.width//2, other._gameObject.sprite.height//2) return bool(mask1.overlap(mask2, [int(i) for i in offset])) elif not self._gameObject.sprite: if isinstance(other, tuple) or isinstance(other, vec): if self._gameObject.body: return self._gameObject.body.point_query(other) elif self._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.point_query(other) else: if self._gameObject.body: return self._gameObject.body.collide(other._gameObject.body) elif self._gameObject.tiledmap_bodies: if other._gameObject.body: return self._gameObject.tiledmap_bodies.collide(other._gameObject.body) elif other._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.collide(other._gameObject.tiledmap_bodies) else: return False def separate(self, other): # 不要检测是否与get_mouse_pos()函数的分离,因为只能检测和固定点之间的分离 if other not in self.collision_dict: self.collision_dict[other] = False if not self.collide(other) and self.collision_dict[other]: self.collision_dict[other] = False return True else: if self.collide(other): self.collision_dict[other] = True else: self.collision_dict[other] = False return False def distance(self, other): if isinstance(other, tuple): return self._gameObject.pos.distance_to(other) else: return self._gameObject.pos.distance_to(other._gameObject.pos) def say(self, text = None): if not self._dialogBox: self._dialogBox = DialogBox(self) if text: self._dialogBox.show() self._dialogBox.say(text) else: self._dialogBox.hide() if IS_UPDATED: update() def kill(self): self._gameObject.kill() if self._dialogBox: self._dialogBox.kill() def apply_force(self, x, *y): if self._gameObject.body: if y: self._gameObject.body.apply_impulse_at_local_point((x, *y)) else: self._gameObject.body.apply_impulse_at_local_point(x) elif self._gameObject.tiledmap_bodies: if y: self._gameObject.tiledmap_bodies.apply_impulse_at_local_point((x, *y)) else: self._gameObject.tiledmap_bodies.apply_impulse_at_local_point(x) @ property def elasticity(self): if self._gameObject.body: return self._gameObject.body.elasticity elif self._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.elasticity @ elasticity.setter def elasticity(self, e): if self._gameObject.body: self._gameObject.body.elasticity = e elif self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.elasticity = e @ property def friction(self): if self._gameObject.body: return self._gameObject.body.friction elif self._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.friction @ friction.setter def friction(self, f): if self._gameObject.body: self._gameObject.body.friction = f elif self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.friction = f @ property def mass(self): if self._gameObject.body: return self._gameObject.body.mass elif self._gameObject.tiledmap_bodies: return self._gameObject.tiledmap_bodies.mass @ mass.setter def mass(self, m): if self._gameObject.body: self._gameObject.body.mass = m elif self._gameObject.tiledmap_bodies: self._gameObject.tiledmap_bodies.mass = m def body_scale(self, scalex, scaley): if "radius" in self.__dict__: if scaley: print('圆形无法进行不同方向的拉伸') self._gameObject.body.shape.unsafe_set_radius(int(self.radius * scalex)) elif "vertices" in self.__dict__: if scaley: self._gameObject.body.set_vertices(self.vertices, transform=pymunk.Transform(a = scalex, d = scaley)) else: self._gameObject.body.set_vertices(self.vertices, transform=pymunk.Transform(a = scalex, d = scalex)) elif self._gameObject.tiledmap_bodies: if scaley: self._gameObject.tiledmap_bodies.set_vertices(scalex, scaley) else: self._gameObject.tiledmap_bodies.set_vertices(scalex, scalex) else: raise NotImplementedError def _update(self): # 私有方法, 不要重载!! self._just_released = False if self.angular_velocity: self.dir = self.dir.rotate(self.angular_velocity) ''' if sys.getrefcount(self) <= 6: self.kill()''' def update(self): # 允许重载的方法 pass class Character(NewGameObject): ''' 允许通过代码控制其运动的类 ''' def __init__(self, imgs = None, size = None): # 可以通过给出一张图片或图片列表或来实现人物创建 NewGameObject.__init__(self, imgs = imgs, size = size, body_type = "DYNAMIC", sensor = False) class Sensor(NewGameObject): def __init__(self, imgs = None, size = None): # 可以通过给出一张图片或图片列表或来实现人物创建 NewGameObject.__init__(self, imgs = imgs, size = size, body_type = "KINEMATIC", sensor = True) class Wall(NewGameObject): ''' 墙壁,无法运动的物体 ''' def __init__(self, imgs = None, size = None): # 可以通过给出一张图片或图片列表或来实现人物创建 NewGameObject.__init__(self, imgs = imgs, size = size, body_type = "STATIC", sensor = False) self._velocity = vec(0, 0) @ property def velocity(self): return self._velocity @ velocity.setter def velocity(self, v): self._velocity = v def _update(self): super()._update() self.pos += self._velocity class Mouse(Character): def __init__(self, imgs = None): Character.__init__(self, imgs) if imgs: set_mouse_visible(False) def body_scale(self, scalex, scaley = None): pass def get_pos(self): return get_mouse_pos() def get_rel(self): return get_mouse_rel() def get_clicked(self): return get_mouse_clicked() def get_just_clicked(self): return get_mouse_just_clicked() def get_just_released(self): return get_mouse_just_released() def update(self): self.goto(get_mouse_pos()) def load_image(img): return pygame.image.load(img) def bgpic(img): if isinstance(img, str): bg = Character(img) else: bg = img if isinstance(bg, TiledMap): global_var.CAMERA = Camera((bg.width, bg.height)) else: global_var.CAMERA = Camera((bg._gameObject.sprite.width, bg._gameObject.sprite.height))
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/API.py
API.py
from .config import * from .camera import Camera from .physics import * def setup(*size): if (not isinstance(size[0], int)) or (not isinstance(size[1], int)): raise TypeError('类型错误:参数必须为整数') if len(size) != 2: raise TypeError('类型错误:参数数目错误,只允许两个参数') global_var.SCREEN = Screen(size) global_var.WIDTH, global_var.HEIGHT = size global_var.ALL_SPRITES = pygame.sprite.LayeredDirty() global_var.CAMERA = Camera(size) global_var.SPACE = pymunk.Space() global_var.SPACE.collision_bias = 0 global_var.SPACE.gravity = (0, 0) global_var.BODIES = BodiesGroup() global_var.TMBG = TiledMapBodiesGroup() return global_var.SCREEN def title(title): pygame.display.set_caption(title) def update(): global_var.SCREEN.update() global_var.JUST_RELEASED = False def save_screen(name): global_var.SCREEN.save_name = name def done(): while True: global_var.SCREEN.update() class Screen(): def __init__(self, size): self.size = size self._screen = pygame.display.set_mode(size) self._clock = pygame.time.Clock() self.save_name = None def update(self): global_var.EVENTS = pygame.event.get() for event in global_var.EVENTS: if event.type == pygame.QUIT: pygame.quit() os._exit(0) global_var.GROUP.update() global_var.BODIES.update() global_var.TMBG.update() global_var.SPACE.step(1/60) rects = global_var.CAMERA.update() size = vec(global_var.CAMERA.size) * global_var.CAMERA.scl self._screen.blit(pygame.transform.scale(global_var.CAMERA.surface, [int(i) for i in size]), \ global_var.CAMERA.offset + (vec(self.size) - size)//2) self.draw() if self.save_name: pygame.image.save(self._screen, self.save_name) self.save_name = None pygame.display.update() self._clock.tick(40) self._screen.fill(BLACK) def draw(self): for p1, p2, color, width in global_var.LINES: pygame.draw.lines(self._screen, color, 0, [p1, p2], width) global_var.LINES = []
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/screen.py
screen.py
from .config import * import pytmx from pytmx.util_pygame import load_pygame from .camera import Camera class TiledMap(): def __init__(self, tilemap): tm = load_pygame(tilemap, pixelalpha = False) self.width = tm.width * tm.tilewidth self.height = tm.height * tm.tileheight self._tmxdata = tm self._get_objects() def render(self, surface): ti = self._tmxdata.get_tile_image_by_gid for layer in self._tmxdata.visible_layers: if isinstance(layer, pytmx.TiledTileLayer): for x, y, gid in layer: tile = ti(gid) if tile: surface.blit(tile, (x * self._tmxdata.tilewidth, y * self._tmxdata.tileheight)) def make_map(self): temp_surface = pygame.Surface((self.width, self.height)).convert_alpha() temp_surface.fill((0,0,0,0)) self.render(temp_surface) return temp_surface @ property def objects(self): objects = [] for obj in self._tmxdata.objects: obj.x = obj.x - (self.width - obj.width) // 2 obj.y = (self.height - obj.height) // 2 - obj.y objects.append(obj) return objects def _get_objects(self, name = None): from .API import NewGameObject from .game_object import GameObject from .physics import Body, TiledMapBodies from .textbox import DialogBox for obj in self.objects: if obj.name == name or name == None: if 'points' in obj.__dict__: points = [] for x, y in obj.points: x = x - self.width // 2 y = self.height // 2 - y points.append((x, y)) obj.points = points else: if obj.width == 0: obj.width = 20 obj.height = 20 points = [(obj.x - obj.width // 2, obj.y - obj.height // 2), (obj.x - obj.width // 2, obj.y + obj.height // 2), (obj.x + obj.width // 2, obj.y - obj.height // 2), (obj.x + obj.width // 2, obj.y + obj.height // 2)] obj.points = points def get_objects(self, name = None): objects = [] for obj in self.objects: if obj.name == name or name == None: objects.append(obj) return objects
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/tiledmap.py
tiledmap.py
from .config import * #pygame.key.set_repeat(300, 100) def get_mouse_pos(): # 获得鼠标坐标 return pygame2Cartesian(pygame.mouse.get_pos()) def get_mouse_rel(): # 获得鼠标运动 ''' x, y = pygame.mouse.get_rel() return vec(x, -y) ''' for event in global_var.EVENTS: if event.type == MOUSEMOTION: x, y = event.rel return vec(x, -y) else: return vec(0, 0) def get_mouse_clicked(): # 检测鼠标左键是否在按下的状态下 for event in global_var.EVENTS: if event and event.type == MOUSEBUTTONDOWN: global_var.GET_CLICKED = True get_mouse_just_released() if global_var.GET_CLICKED: return True else: return False def get_mouse_just_clicked(): # 检测鼠标是否刚刚被按下 for event in global_var.EVENTS: if event and event.type == MOUSEBUTTONDOWN: global_var.GET_CLICKED = True return True else: return False def get_mouse_just_released(): # 检测鼠标是否刚刚被松开 if global_var.JUST_RELEASED: return True get_mouse_just_clicked() if global_var.GET_CLICKED: for event in global_var.EVENTS: if event and event.type == MOUSEBUTTONUP: global_var.GET_CLICKED = False global_var.JUST_RELEASED = True if global_var.GET_CLICKED: return False else: return True else: return False def key_pressed(key = None): if not key: if 1 in pygame.key.get_pressed(): return True else: return False if pygame.key.get_pressed()[key]: return True else: return False def key_just_pressed(*keys): keyEvents = [] for event in global_var.EVENTS: if event.type == KEYDOWN: keyEvents.append(event.key) if not keys: return keyEvents for key in keys: if key not in keyEvents: break else: return True return False def key_released(*keys): keyEvents = [] for event in global_var.EVENTS: if event.type == KEYUP: keyEvents.append(event.key) if not keys: return keyEvents for key in keys: if key not in keyEvents: break else: return True return False
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/events.py
events.py
from .config import * from .constraints import * class BodiesGroup(): def __init__(self): self._group = [] def update(self): for body in self._group: body.update() def add(self, body): self._group.append(body) def remove(self, body): self._group.remove(body) class TiledMapBodiesGroup(): def __init__(self): self._group = [] def update(self): for tiledmapbodies in self._group: tiledmapbodies.update() def add(self, tiledmapbodies): self._group.append(tiledmapbodies) def remove(self, tiledmapbodies): self._group.remove(tiledmapbodies) class Body(): def __init__(self, body_type, shape, size, sensor): mass = 1 moment = 1 if shape == 'CIRCLE': moment = pymunk.moment_for_circle(mass, 0, size) if body_type == 'KINEMATIC': self.body = pymunk.Body(mass, moment, body_type = pymunk.Body.KINEMATIC) elif body_type == 'DYNAMIC': self.body = pymunk.Body(mass, moment, body_type = pymunk.Body.DYNAMIC) elif body_type == 'STATIC': self.body = pymunk.Body(mass, moment, body_type = pymunk.Body.STATIC) self.body.position = 0,0 if shape == 'CIRCLE': self.shape = pymunk.Circle(self.body, size) elif shape == 'BOX': width, height = size points = [(-width//2, -height//2), (-width//2, height//2), (width//2,height//2), (width//2, -height//2)] self.shape = pymunk.Poly(self.body, points) elif shape == 'POLY': self.shape = pymunk.Poly(self.body, size) self.shape.sensor = sensor global_var.SPACE.add(self.body, self.shape) global_var.BODIES.add(self) def set_parent(self, parent): self._parent = parent if 'offset' in self.__dict__: self.shape.body.position = self._parent.pos + self.offset else: self.shape.body.position = self._parent.pos def set_pos(self, pos): self.shape.body.position = pos global_var.SPACE.reindex_shapes_for_body(self.body) def update(self): if 'offset' not in self.__dict__: self._parent.pos = self.shape.body.position self._parent.rot = self.body.angle / 3.1415926 * 180 def collide(self, other): if self.shape.shapes_collide(other.shape).points: return True else: return False def point_query(self, p): if self.shape.point_query(p)[0] <= 0: return True else: return False def kill(self): global_var.SPACE.remove(self.body, self.shape) global_var.BODIES.remove(self) def set_rot(self, rot): self.body.angle = rot / 180 * 3.1415926 global_var.SPACE.reindex_shapes_for_body(self.body) @ property def velocity(self): return self.body.velocity @ velocity.setter def velocity(self, v): self.body.velocity = v @ property def angular_velocity(self): return self.body.angular_velocity @ angular_velocity.setter def angular_velocity(self, av): self.body.angular_velocity = av def apply_impulse_at_local_point(self, impulse): self.body.apply_impulse_at_local_point(impulse) @ property def elasticity(self): return self.shape.elasticity @ elasticity.setter def elasticity(self, e): self.shape.elasticity = e @ property def friction(self): return self.shape.friction @ friction.setter def friction(self, f): self.shape.friction = f @ property def mass(self): return self.body.mass @ mass.setter def mass(self, m): self.body.mass = m def set_vertices(self, vertices, transform): self.shape.unsafe_set_vertices(vertices, transform) class TiledMapBodies(list): def __init__(self, body_type, objs, sensor): list.__init__(self) global_var.TMBG.add(self) self._velocity = vec(0, 0) self._angular_velocity = 0 self._mass = 1 self._friction = 0 self._elasticity = 1 self.pos = vec(0, 0) for obj in objs: try: body = Body(body_type, 'POLY', obj.points, sensor) except: print(obj.__dict__) body.offset = vec(0, 0) body.vertices = body.shape.get_vertices() body.offsetrot = 0 body.offsetscale = vec(1, 1) body.set_parent(self) self.append(body) if body_type == 'DYNAMIC': print('不建议将网格地图设置为Character') dict = [] for body in self: for other in self: if body != other and {body, other} not in dict: connect(body, other) dict.append({body, other}) def set_parent(self, parent): self._parent = parent self.pos = self._parent.pos def set_pos(self, pos): self.pos = pos for body in self: body.offset_scaled = vec(body.offset[0] * body.offsetscale[0], body.offset[1] * body.offsetscale[1]) body.body.position = self.pos + body.offset_scaled.rotate(body.offsetrot) global_var.SPACE.reindex_shapes_for_body(body.body) def update(self): positions = vec(0,0) for body in self: positions += body.body.position positions /= len(self) self.pos = positions self._parent.pos = self.pos self._parent.rot = self[0].body.angle / 3.1415926 * 180 def collide(self, other): for body in self: if body.shape.shapes_collide(other.shape).points: return True else: return False def point_query(self, p): for body in self: if body.shape.point_query(p)[0] <= 0: return True else: return False def kill(self): for body in self: global_var.SPACE.remove(body.body, body.shape) global_var.BODIES.remove(body) def set_rot(self, rot): for body in self: body.body.angle = rot / 180 * 3.1415926 body.offsetrot = rot global_var.SPACE.reindex_shapes_for_body(body.body) @ property def velocity(self): return self._velocity @ velocity.setter def velocity(self, v): self._velocity = v for body in self: body.body.velocity = v @ property def angular_velocity(self): return self._angular_velocity @ angular_velocity.setter def angular_velocity(self, av): self._angular_velocity = av for body in self: body.body.angular_velocity = av def apply_impulse_at_local_point(self, pos): for body in self: body.body.apply_impulse_at_local_point(pos) @ property def elasticity(self): return self._elasticity @ elasticity.setter def elasticity(self, e): self._elasticity = e for body in self: body.body.elasticity = e @ property def friction(self): return self._friction @ friction.setter def friction(self, f): self._friction = f for body in self: body.body.friction = f @ property def mass(self): return self._mass @ mass.setter def mass(self, m): self._mass = m for body in self: body.body.mass = m def set_vertices(self, scalex, scaley): for body in self: body.set_vertices(body.vertices, transform=pymunk.Transform(a = scalex, d = scaley)) body.offsetscale = vec(scalex, scaley)
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/physics.py
physics.py
from .config import * def camera_offset(p): o = vec(global_var.SCREEN.size) - vec(global_var.CAMERA.size) newp = p - o //2 newp = (int(newp[0]), int(newp[1])) return newp class NewDrawOptions(pymunk.SpaceDebugDrawOptions): def __init__(self, surface): self.surface = surface super(NewDrawOptions, self).__init__() def draw_circle(self, pos, angle, radius, outline_color, fill_color): p = pymunk2Cartesian(pos, self.surface) pygame.draw.circle(self.surface, fill_color, p, _rndint(radius), 0) circle_edge = pos + Vec2d(radius, 0).rotated(angle) p2 = pymunk2Cartesian(circle_edge, self.surface) line_r = 2 if radius > 20 else 1 pygame.draw.lines(self.surface, outline_color, False, [p,p2], line_r) def draw_segment(self, a, b, color): p1 = pymunk2Cartesian(a, self.surface) p2 = pymunk2Cartesian(b, self.surface) pygame.draw.aalines(self.surface, color, False, [p1,p2]) def draw_fat_segment(self, a, b, radius, outline_color, fill_color): p1 = pymunk2Cartesian(a, self.surface) p2 = pymunk2Cartesian(b, self.surface) r = _rndint(max(1, radius*2)) pygame.draw.lines(self.surface, fill_color, False, [p1,p2], r) if r > 2: delta = ( p2[0]-p1[0], p2[1]-p1[1] ) orthog = [ delta[1], -delta[0] ] scale = radius / (orthog[0]*orthog[0] + orthog[1]*orthog[1])**0.5 orthog[0]*=scale; orthog[1]*=scale points = [ ( p1[0]-orthog[0], p1[1]-orthog[1] ), ( p1[0]+orthog[0], p1[1]+orthog[1] ), ( p2[0]+orthog[0], p2[1]+orthog[1] ), ( p2[0]-orthog[0], p2[1]-orthog[1] ) ] pygame.draw.polygon(self.surface, fill_color, points) pygame.draw.circle(self.surface, fill_color, (_rndint(p1[0]),_rndint(p1[1])), _rndint(radius)) pygame.draw.circle(self.surface, fill_color, (_rndint(p2[0]),_rndint(p2[1])), _rndint(radius)) def draw_polygon(self, verts, radius, outline_color, fill_color): ps = [pymunk2Cartesian(v, self.surface) for v in verts] ps += [ps[0]] pygame.draw.polygon(self.surface, fill_color, ps) if radius > 0: for i in range(len(verts)): a = verts[i] b = verts[(i+1) % len(verts)] self.draw_fat_segment(a, b, radius, outline_color, outline_color) def draw_dot(self, size, pos, color): p = pymunk2Cartesian(pos, self.surface) pygame.draw.circle(self.surface, color, p, _rndint(size), 0) def pymunk2Cartesian(p, surface): return camera_offset((int(p[0] + global_var.WIDTH // 2), int(global_var.HEIGHT // 2 - p[1]))) def from_pygame(p, surface): """Convenience method to convert pygame surface local coordinates to pymunk coordinates """ return to_pygame(p,surface) def _rndint(x): return int(round(x))
yuanmaxiong1
/yuanmaxiong1-2.0-py3-none-any.whl/dianyi/draw_options.py
draw_options.py
__author__ = 'Mingqi Yuan' """ Implementation of the Proximal Policy Optimization. """ from torch import optim from torch.nn import functional as F from torch.distributions import Categorical import pandas as pd import numpy as np import torch import sys import os sys.path.append(os.path.dirname(__file__) + os.sep + '../') from nn.ActorDiscrete import ActorDis from nn.CriticStateOnly import CriticSO from replayer.PPOReplayer import PPOReplayer class PPO: def __init__( self, device, state_dim, action_dim, actor_kwargs, critic_kwargs, det=False, gamma=0.99, lambd=0.99, lr=1e-4, batch_size=64, batches=1, max_grad_norm=0.5 ): self.device = device self.state_dim = state_dim self.action_dim = action_dim self.gamma = gamma self.lambd = lambd self.lr = lr self.batch_size = batch_size self.batches = batches self.max_grad_norm = max_grad_norm self.det = det self.actor = ActorDis(actor_kwargs) self.critic = CriticSO(critic_kwargs) self.actor.to(self.device) self.critic.to(self.device) self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=self.lr) self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=self.lr) self.trajectory = [] self.replayer = PPOReplayer() def learn(self, state, action, reward, next_state, done): self.trajectory.append([state, action, reward, done]) if done: ''' reconstruct the data ''' df = pd.DataFrame( np.array(self.trajectory, dtype=object).reshape(-1, 4), columns=['state', 'action', 'reward', 'done']) state_tensor = torch.FloatTensor(np.stack(df['state'])).to(self.device) action_tensor = torch.from_numpy(np.stack(df['action']).astype('int64')).to(self.device) v_tensor = self.critic(state_tensor) df['v'] = v_tensor.detach().cpu().numpy() prob_tensor = self.actor(state_tensor) pi_tensor = prob_tensor.gather(1, action_tensor.unsqueeze(1)).squeeze(1) df['prob'] = pi_tensor.detach().cpu().numpy() df['next_v'] = df['v'].shift(-1).fillna(0.) df['u'] = df['reward'] + self.gamma * df['next_v'] df['delta'] = df['u'] - df['v'] df['return'] = df['reward'] df['advantage'] = df['delta'] for i in df.index[-2::-1]: df.loc[i, 'return'] += self.gamma * df.loc[i + 1, 'return'] df.loc[i, 'advantage'] += self.gamma * self.lambd * df.loc[i + 1, 'advantage'] self.replayer.store(df) for i in range(self.batches): states_, actions_, old_probs_, advantages_, returns_ = \ self.replayer.sample(size=self.batch_size) batch_state = torch.FloatTensor(states_).to(self.device) batch_action = torch.from_numpy(actions_).to(self.device) batch_old_prob = torch.FloatTensor(old_probs_).to(self.device) batch_advantage = torch.FloatTensor(advantages_).to(self.device) batch_return = torch.FloatTensor(returns_).to(self.device) ''' update actor ''' pi_tensor = self.actor(batch_state).gather( 1, batch_action.unsqueeze(1)).squeeze(1) surrogate_advantage_tensor = (pi_tensor / batch_old_prob) * batch_advantage clip_times_advantage_tensor = 0.1 * surrogate_advantage_tensor max_surrogate_advantage_tensor = batch_advantage + torch.where( batch_advantage > 0., clip_times_advantage_tensor, -clip_times_advantage_tensor) clipped_surrogate_advantage_tensor = torch.min( surrogate_advantage_tensor, max_surrogate_advantage_tensor) actor_loss_tensor = - clipped_surrogate_advantage_tensor.mean() self.optimizer_actor.zero_grad() actor_loss_tensor.backward() torch.nn.utils.clip_grad_norm(self.actor.parameters(), self.max_grad_norm) self.optimizer_actor.step() ''' update critic ''' pred_vs = self.critic(batch_state) critic_loss_tensor = F.mse_loss(pred_vs[:, 0], batch_return) self.optimizer_critic.zero_grad() critic_loss_tensor.backward() torch.nn.utils.clip_grad_norm(self.critic.parameters(), self.max_grad_norm) self.optimizer_critic.step() ''' reset the replayer ''' self.trajectory = [] self.replayer = PPOReplayer() def decide(self, state): with torch.no_grad(): state_tensor = torch.from_numpy(state).float() state_tensor = torch.unsqueeze(state_tensor, dim=0) prob = self.actor(state_tensor.to(self.device)).clamp(1e-4, 0.999) ''' deterministic policy ''' if self.det: action = torch.argmax(prob, dim=1) else: policy = Categorical(prob) action = policy.sample() return action.detach().cpu().numpy()[0] def save(self, save_dir, epoch): torch.save(self.actor, '{}/ppo_policy_epoch{}.pth'.format(save_dir, epoch))
yuanrl
/sarl/apis/PPO.py
PPO.py
__author__ = 'Mingqi Yuan' """ Implementation of the Trust Region Policy Optimization. """ from torch import optim, autograd from torch.nn import functional as F from torch.distributions import Categorical import pandas as pd import numpy as np import torch import sys import os sys.path.append(os.path.dirname(__file__) + os.sep + '../') from nn.ActorDiscrete import ActorDis from nn.CriticStateOnly import CriticSO from replayer.PPOReplayer import PPOReplayer class TRPO: def __init__( self, device, state_dim, action_dim, actor_kwargs, critic_kwargs, det=False, gamma=0.99, max_kl=0.01, lr=1e-4, batch_size=64, batches=1, max_grad_norm=0.5 ): self.device = device self.state_dim = state_dim self.action_dim = action_dim self.gamma = gamma self.max_kl = max_kl self.lr = lr self.batch_size = batch_size self.batches = batches self.max_grad_norm = max_grad_norm self.det = det self.actor = ActorDis(actor_kwargs) self.critic = CriticSO(critic_kwargs) self.actor.to(self.device) self.critic.to(self.device) self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=self.lr) self.trajectory = [] self.replayer = PPOReplayer() def learn(self, state, action, reward, next_state, done): self.trajectory.append([state, action, reward, done]) if done: ''' reconstruct the data ''' df = pd.DataFrame( np.array(self.trajectory, dtype=object).reshape(-1, 4), columns=['state', 'action', 'reward', 'done']) state_tensor = torch.FloatTensor(np.stack(df['state'])).to(self.device) action_tensor = torch.from_numpy(np.stack(df['action']).astype('int64')).to(self.device) v_tensor = self.critic(state_tensor) df['v'] = v_tensor.detach().cpu().numpy() prob_tensor = self.actor(state_tensor) pi_tensor = prob_tensor.gather(1, action_tensor.unsqueeze(1)).squeeze(1) df['prob'] = pi_tensor.detach().cpu().numpy() df['next_v'] = df['v'].shift(-1).fillna(0.) df['u'] = df['reward'] + self.gamma * df['next_v'] df['delta'] = df['u'] - df['v'] df['return'] = df['reward'] df['advantage'] = df['delta'] for i in df.index[-2::-1]: df.loc[i, 'return'] += self.gamma * df.loc[i + 1, 'return'] df.loc[i, 'advantage'] += self.gamma * df.loc[i + 1, 'advantage'] self.replayer.store(df) for i in range(self.batches): states_, actions_, old_probs_, advantages_, returns_ = \ self.replayer.sample(size=self.batch_size) batch_state = torch.FloatTensor(states_).to(self.device) batch_action = torch.from_numpy(actions_).to(self.device) batch_old_prob = torch.FloatTensor(old_probs_).to(self.device) batch_advantage = torch.FloatTensor(advantages_).to(self.device) batch_return = torch.FloatTensor(returns_).to(self.device) ''' update actor ''' ''' get first order gradient: g ''' pi_tensor = self.actor(batch_state).gather(1, batch_action.unsqueeze(1)).squeeze(1) surrogate_advantage_tensor = (pi_tensor / batch_old_prob) * batch_advantage actor_loss_tensor = surrogate_advantage_tensor.mean() actor_loss_grads = autograd.grad(actor_loss_tensor, self.actor.parameters()) actor_loss_grads = torch.cat([grad.view(-1) for grad in actor_loss_grads]).detach() ''' get the conjugate gradient: Fx=g ''' def f(x): prob_tensor = self.actor(batch_state) prob_old_tensor = prob_tensor.detach() kld_tensor = (prob_old_tensor * torch.log( (prob_old_tensor / prob_tensor).clamp(1e-6, 1e6))).sum(axis=1) kld_loss_tensor = kld_tensor.mean() grads = autograd.grad(kld_loss_tensor, self.actor.parameters(), create_graph=True) flatten_grad_tensor = torch.cat([grad.view(-1) for grad in grads]) grad_matmul_x = torch.dot(flatten_grad_tensor, x) grad_grads = autograd.grad(grad_matmul_x, self.actor.parameters()) flatten_grad_grad = torch.cat([grad.contiguous().view(-1) for grad in grad_grads]).detach() fx = flatten_grad_grad + x * 0.01 return fx x, fx = self.conjugate_gradient(f, actor_loss_grads) # ... calculate natural gradient: sqrt(...) g natural_gradient_tensor = torch.sqrt(2 * self.max_kl / torch.dot(fx, x)) * x # ... line search def set_actor_net_params(flatten_params): begin = 0 for param in self.actor.parameters(): end = begin + param.numel() param.data.copy_(flatten_params[begin:end].view(param.size())) begin = end old_params = torch.cat([param.view(-1) for param in self.actor.parameters()]) expected_improve = torch.dot(actor_loss_grads, natural_gradient_tensor) for learning_step in [0., ] + [.5 ** j for j in range(10)]: new_params = old_params + learning_step * natural_gradient_tensor set_actor_net_params(new_params) new_pi_tensor = self.actor(batch_state).gather(1, batch_action.unsqueeze(1)).squeeze(1) new_pi_tensor = new_pi_tensor.detach() surrogate_tensor = (new_pi_tensor / pi_tensor) * batch_advantage objective = surrogate_tensor.mean().item() if np.isclose(learning_step, 0.): old_objective = objective else: # Armijo condition if objective - old_objective > 0.1 * expected_improve * learning_step: break # improved, save the weight else: set_actor_net_params(old_params) ''' update critic ''' pred_vs = self.critic(batch_state) critic_loss_tensor = F.mse_loss(pred_vs[:, 0], batch_return) self.optimizer_critic.zero_grad() critic_loss_tensor.backward() torch.nn.utils.clip_grad_norm(self.critic.parameters(), self.max_grad_norm) self.optimizer_critic.step() ''' reset the replayer ''' self.trajectory = [] self.replayer = PPOReplayer() def conjugate_gradient(self, f, b, iter_count=10, epsilon=1e-12, tol=1e-6): x = b * 0. r = b.clone() p = b.clone() rho = torch.dot(r, r) for i in range(iter_count): z = f(p) alpha = rho / (torch.dot(p, z) + epsilon) x += alpha * p r -= alpha * z rho_new = torch.dot(r, r) p = r + (rho_new / rho) * p rho = rho_new if rho < tol: break return x, f(x) def decide(self, state): with torch.no_grad(): state_tensor = torch.from_numpy(state).float() state_tensor = torch.unsqueeze(state_tensor, dim=0) prob = self.actor(state_tensor.to(self.device)).clamp(1e-4, 0.999) ''' deterministic policy ''' if self.det: action = torch.argmax(prob, dim=1) else: policy = Categorical(prob) action = policy.sample() return action.detach().cpu().numpy()[0] def save(self, save_dir, epoch): torch.save(self.actor, '{}/trpo_policy_epoch{}.pth'.format(save_dir, epoch))
yuanrl
/sarl/apis/TRPO.py
TRPO.py
__author__ = 'Mingqi Yuan' """ Implementation of the Deep deterministic policy gradient algorithm. """ from torch import optim from torch.nn import functional as F import numpy as np import torch import sys import os sys.path.append(os.path.dirname(__file__) + os.sep + '../') from nn.ActorContinuous import ActorCont from nn.CriticStateAction import CriticSA from replayer.QMIXReplayer import DQNReplayer from noise.OrnsteinUhlenbeckProcess import OUProcess class DDPG: def __init__( self, device, state_dim, action_dim, action_low, action_high, actor_kwargs, critic_kwargs, replayer_capacity=20000, replayer_initial_transitions=2000, gamma=0.99, tau=0.005, noise_scale=0.1, explore=True, batches=1, batch_size=64, lr=1e-3 ): self.device = device self.state_dim = state_dim self.action_dim = action_dim self.action_low = action_low self.action_high = action_high self.gamma = gamma self.tau = tau self.noise_scale = noise_scale self.noise = OUProcess(size=(action_dim,)) self.noise.reset() self.explore = explore self.batches = batches self.batch_size = batch_size self.lr = lr self.replayer_initial_transitions = replayer_initial_transitions self.replayer = DQNReplayer(replayer_capacity) self.actor_eval = ActorCont(actor_kwargs) self.actor_target = ActorCont(actor_kwargs) self.critic_eval = CriticSA(critic_kwargs) self.critic_target = CriticSA(critic_kwargs) self.actor_eval.to(self.device) self.actor_target.to(self.device) self.critic_eval.to(self.device) self.critic_target.to(self.device) self.optimizer_actor_eval = optim.Adam(self.actor_eval.parameters(), lr=self.lr) self.optimizer_critic_eval = optim.Adam(self.critic_eval.parameters(), lr=self.lr) self.actor_target.load_state_dict(self.actor_eval.state_dict()) self.critic_target.load_state_dict(self.critic_eval.state_dict()) def update_target_net(self, target_net, eval_net): for target_params, params in zip(target_net.parameters(), eval_net.parameters()): target_params.data.copy_( target_params.data * (1.0 - self.tau) + params.data * self.tau ) def decide(self, state): if self.explore and self.replayer.count < \ self.replayer_initial_transitions: return np.random.uniform(self.action_low, self.action_high) state_tensor = torch.FloatTensor(state).to(self.device) state_tensor = torch.unsqueeze(state_tensor, dim=0) action = self.actor_eval(state_tensor).detach().cpu().numpy()[0] if self.explore: noise = self.noise() action = np.clip(action + noise, self.action_low, self.action_high)[0] return action def learn(self, state, action, reward, next_state, done): self.replayer.store(state, action, reward, next_state, done) if self.replayer.count >= self.replayer_initial_transitions: if done: self.noise.reset() for batch in range(self.batches): states_, actions_, rewards_, next_states_, dones_ = \ self.replayer.sample(self.batch_size) batch_state = torch.FloatTensor(states_).to(self.device) batch_action = torch.FloatTensor(actions_).to(self.device) batch_reward = torch.FloatTensor(rewards_).to(self.device) batch_next_state = torch.FloatTensor(next_states_).to(self.device) batch_done = torch.from_numpy(dones_).to(self.device) ''' update critic ''' batch_next_action = self.actor_target(batch_next_state) noise_tensor = (0.2 * torch.randn_like(batch_action.unsqueeze(1), dtype=torch.float)) batch_next_action = (batch_next_action + noise_tensor).clamp(self.action_low, self.action_high) next_qs = self.critic_target(batch_next_state, batch_next_action) qs = self.critic_eval(batch_state, batch_action.unsqueeze(1)).squeeze(1) q_targets = batch_reward + self.gamma * torch.logical_not(batch_done) * next_qs[:, 0] self.optimizer_critic_eval.zero_grad() critic_loss = F.mse_loss(qs, q_targets) critic_loss.backward() self.optimizer_critic_eval.step() ''' update actor ''' action_tensor = self.actor_eval(batch_state) action_tensor = action_tensor.clamp(self.action_low, self.action_high) q_tensor = self.critic_eval(batch_state, action_tensor) self.optimizer_actor_eval.zero_grad() actor_loss = - q_tensor.mean() actor_loss.backward() self.optimizer_actor_eval.step() ''' update target networks ''' self.update_target_net(self.actor_target, self.actor_eval) self.update_target_net(self.critic_target, self.critic_eval) def save(self, save_dir, epoch): torch.save(self.actor_eval, '{}/ddpg_policy_epoch{}.pth'.format(save_dir, epoch))
yuanrl
/sarl/apis/DDPG.py
DDPG.py
__author__ = 'Mingqi Yuan' """ Implementation of the Deep Q-learning algorithm. """ from torch import optim from torch.nn import functional as F import numpy as np import torch import sys import os sys.path.append(os.path.dirname(__file__) + os.sep + '../') from nn.QNetworkDiscrete import QND from replayer.DQNReplayer import DQNReplayer class DeepQ: def __init__( self, device, state_dim, action_dim, qnet_kwargs, gamma=0.99, epsilon=0.001, replayer_capacity=10000, replayer_initial_transitions=5000, batch_size=64, lr=1e-3 ): self.device = device self.state_dim = state_dim self.action_dim = action_dim self.gamma = gamma self.epsilon = epsilon self.batch_size = batch_size self.lr = lr self.replayer = DQNReplayer(replayer_capacity) self.replayer_initial_transitions = replayer_initial_transitions self.eval_net = QND(qnet_kwargs) self.target_net = QND(qnet_kwargs) self.eval_net.to(self.device) self.target_net.to(self.device) self.optimizer_eval_net = optim.Adam(self.eval_net.parameters(), lr=self.lr) self.target_net.load_state_dict(self.eval_net.state_dict()) def learn(self, state, action, reward, next_state, done): self.replayer.store(state, action, reward, next_state, done) if self.replayer.count >= self.replayer_initial_transitions: states_, actions_, rewards_, next_states_, dones_ = \ self.replayer.sample(self.batch_size) batch_state = torch.FloatTensor(states_).to(self.device) batch_action = torch.from_numpy(actions_).to(self.device) batch_reward = torch.FloatTensor(rewards_).to(self.device) batch_next_state = torch.FloatTensor(next_states_).to(self.device) batch_done = torch.from_numpy(dones_).to(self.device) next_qs = self.target_net(batch_next_state) next_max_qs, _ = torch.max(next_qs, dim=1) q_targets = batch_reward + self.gamma * torch.logical_not(batch_done) * next_max_qs qs = self.eval_net(batch_state) qs = torch.gather(qs, 1, batch_action.unsqueeze(1)).squeeze(1) ''' update network ''' self.optimizer_eval_net.zero_grad() eval_net_loss = F.mse_loss(qs, q_targets) eval_net_loss.backward() self.optimizer_eval_net.step() if done: self.target_net.load_state_dict(self.eval_net.state_dict()) def decide(self, state): # epsilon-greedy policy if np.random.rand() < self.epsilon: return np.random.randint(self.action_dim) state_tensor = torch.FloatTensor(state).to(self.device) state_tensor = torch.unsqueeze(state_tensor, 0) qs = self.eval_net(state_tensor) action = torch.argmax(qs, dim=1) return action.detach().cpu().numpy()[0] def save(self, save_dir, epoch): torch.save(self.eval_net, '{}/ql_policy_epoch{}.pth'.format(save_dir, epoch))
yuanrl
/sarl/apis/DeepQ.py
DeepQ.py
__author__ = 'Mingqi Yuan' """ Implementation of the Deep deterministic policy gradient algorithm. """ from torch import optim from torch.nn import functional as F from torch.distributions import Categorical import torch import sys import os sys.path.append(os.path.dirname(__file__) + os.sep + '../') from nn.ActorDiscrete import ActorDis from nn.CriticStateOnly import CriticSO from replayer.QMIXReplayer import DQNReplayer class SACDiscrete: def __init__( self, device, state_dim, action_dim, actor_kwargs, critic_kwargs, det=False, gamma=0.99, tau=0.005, replayer_capacity=10000, replayer_initial_transitions=5000, lr=1e-4, batch_size=64, batches=1 ): self.device = device self.state_dim = state_dim self.action_dim = action_dim self.gamma = gamma self.tau = tau self.lr = lr self.batch_size = batch_size self.batches = batches self.replayer = DQNReplayer(replayer_capacity) self.replayer_initial_transitions = replayer_initial_transitions # self.entropy_target = 0.98 * (-np.log(1 / self.action_dim)) # self.log_alpha = torch.zeros(1, requires_grad=True, device=self.device) # self.alpha = self.log_alpha.exp() self.alpha = 0.02 self.det = det self.actor = ActorDis(actor_kwargs) self.qf1_eval = CriticSO(critic_kwargs) self.qf1_target = CriticSO(critic_kwargs) self.qf2_eval = CriticSO(critic_kwargs) self.qf2_target = CriticSO(critic_kwargs) self.actor.to(self.device) self.qf1_eval.to(self.device) self.qf1_target.to(self.device) self.qf2_eval.to(self.device) self.qf2_target.to(self.device) self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=self.lr) self.optimizer_qf1 = optim.Adam(self.qf1_eval.parameters(), lr=self.lr) self.optimizer_qf2 = optim.Adam(self.qf2_eval.parameters(), lr=self.lr) # self.optimizer_alpha = optim.Adam([self.log_alpha], lr=self.lr) ''' load weights ''' self.qf1_target.load_state_dict(self.qf1_eval.state_dict()) self.qf2_target.load_state_dict(self.qf2_eval.state_dict()) def update_target_net(self, target_net, eval_net): for target_params, params in zip(target_net.parameters(), eval_net.parameters()): target_params.data.copy_( target_params.data * (1.0 - self.tau) + params.data * self.tau ) def learn(self, state, action, reward, next_state, done): self.replayer.store(state, action, reward, next_state, done) if self.replayer.count >= self.replayer_initial_transitions: for b in range(self.batches): batch_state, batch_action, batch_reward, batch_next_state, batch_done = \ self.replayer.sample(self.batch_size) batch_state = torch.FloatTensor(batch_state).to(self.device) batch_action = torch.from_numpy(batch_action).to(self.device) batch_reward = torch.FloatTensor(batch_reward).to(self.device) batch_next_state = torch.FloatTensor(batch_next_state).to(self.device) batch_done = torch.FloatTensor(batch_done).to(self.device) ''' update action value function ''' with torch.no_grad(): probs_next = self.actor(batch_next_state).clamp(1e-4, 0.999) qs1_next = self.qf1_target(batch_next_state) qs2_next = self.qf2_target(batch_next_state) qs_next = torch.min(qs1_next, qs2_next) vs_next = probs_next * (qs_next - self.alpha * torch.log(probs_next)) vs_next = torch.sum(vs_next, dim=1) qs_target = batch_reward + self.gamma * torch.logical_not(batch_done) * vs_next self.optimizer_qf1.zero_grad() self.optimizer_qf2.zero_grad() qs1 = self.qf1_eval(batch_state).gather(dim=1, index=batch_action.unsqueeze(1)) qs2 = self.qf2_eval(batch_state).gather(dim=1, index=batch_action.unsqueeze(1)) qf1_loss = F.mse_loss(qs1[:, 0], qs_target) qf2_loss = F.mse_loss(qs2[:, 0], qs_target) qf1_loss.backward() qf2_loss.backward() self.optimizer_qf1.step() self.optimizer_qf2.step() ''' update actor ''' probs = self.actor(batch_state).clamp(1e-4, 0.999) with torch.no_grad(): qs1 = self.qf1_eval(batch_state) qs2 = self.qf2_eval(batch_state) qs = torch.min(qs1, qs2) self.optimizer_actor.zero_grad() actor_loss = self.alpha * probs * torch.log(probs) - probs * qs actor_loss = actor_loss.sum(dim=1).mean() actor_loss.backward() self.optimizer_actor.step() # ''' update temperature ''' # self.optimizer_alpha.zero_grad() # log_probs = (probs * torch.log(probs)).sum(-1) # alpha_loss = - (self.log_alpha * (log_probs.detach() + self.entropy_target)).mean() # alpha_loss.backward() # self.optimizer_alpha.step() # self.alpha = self.log_alpha.exp() ''' update target Q ''' self.update_target_net(self.qf1_target, self.qf1_eval) self.update_target_net(self.qf2_target, self.qf2_eval) def decide(self, state): with torch.no_grad(): state_tensor = torch.from_numpy(state).float() state_tensor = torch.unsqueeze(state_tensor, dim=0) prob = self.actor(state_tensor.to(self.device)).clamp(1e-4, 0.999) ''' deterministic policy ''' if self.det: action = torch.argmax(prob, dim=1) else: policy = Categorical(prob) action = policy.sample() return action.detach().cpu().numpy()[0] def save(self, save_dir, epoch): torch.save(self.actor, '{}/sacd_policy_epoch{}.pth'.format(save_dir, epoch))
yuanrl
/sarl/apis/SACDiscrete.py
SACDiscrete.py
# Yuansfer Python SDK [Yuansfer API](https://docs.yuansfer.com/) ## Requirements The SDK supports the following versions of Python: * Python 3 versions 3.4 and later ## Installation Install the latest SDK using pip: ```sh pip install yuansfer==3.0.4 ``` ## Usage First time with Yuansfer? Here’s how to get started: 1. **Create a Yuansfer Sandbox account.** If you don’t have one already, [sign up for a sandbox account](https://yuansfer.github.io/yuansfer-sandbox-application/?language=english). Now let’s call your first Yuansfer API. Create a python new file, and copy the following code into that file: ```python from yuansfer.client import Client # Create an instance of the API Client # and initialize it with the sandbox credentials client = Client( environment='sandbox', merchantNo='{{REPLACE_MERCHANT_NUMBER}}', storeNo='{{REPLACE_STORE_NUMBER}}', token='{{REPLACE_TOKEN}}' ) ### 1. Online API # Get an instance of the Yuansfer Online API you want call api_online = client.online # Set request payload params = { 'amount':'0.01', 'currency':'USD', 'settleCurrency':'USD', 'vendor':'alipay', 'terminal':'ONLINE', 'reference': datetime.now, 'ipnUrl':"http://zk-tys.yunkeguan.com/ttest/test", 'callbackUrl':"http://zk-tys.yunkeguan.com/ttest/test", 'description':'descrip', 'note':'note' } # Make a Yuansfer Secure Pay request result = api_online.secure_pay(params) # Call the success method to see if the call succeeded if result.is_success(): # Check if the request is successful if result.body['ret_code'] == '000100': # The body property is the resposne from Yuansfer yuansferResponse = result.body['result'] print(yuansferResponse) else: print(result.body['ret_msg']) # Call the error method to see if the call failed elif result.is_error(): print('Error calling OnlineApi.SecurePay') errors = result.errors # An error is returned as a list of errors for error in errors: # Each error is represented as a dictionary for key, value in error.items(): print(f"{key} : {value}") print("\n") ### 2. Offline API # Get an instance of the Yuansfer Offline API you want call api_offline = client.offline # Set request payload params = { 'amount':'0.01', 'currency':'USD', 'settleCurrency':'USD', 'reference': datetime.now } # Make a Yuansfer Instore Create Transaction QR Code request result = offline.instore_create_tran_qrcode(params) # Call the success method to see if the call succeeded if result.is_success(): # Check if the request is successful if result.body['ret_code'] == '000100': # The body property is the resposne from Yuansfer yuansferResponse = result.body['result'] print(yuansferResponse) else: print(result.body['ret_msg']) # Call the error method to see if the call failed elif result.is_error(): print('Error calling OfflineApi.InstoreCreateTranQrcode') errors = result.errors # An error is returned as a list of errors for error in errors: # Each error is represented as a dictionary for key, value in error.items(): print(f"{key} : {value}") print("\n") ### 3. Mobile API # Get an instance of the Yuansfer Mobile API you want call api_mobile = client.mobile # Set request payload params = { 'amount':'0.01', 'currency':'USD', 'settleCurrency':'USD', 'reference': datetime.now, 'vendor':'alipay', 'terminal':'APP' } # Make a Yuansfer Mobile Prepay request result = api_mobile.mobile_prepay(params) # Call the success method to see if the call succeeded if result.is_success(): # Check if the request is successful if result.body['ret_code'] == '000100': # The body property is the resposne from Yuansfer yuansferResponse = result.body['result'] print(yuansferResponse) else: print(result.body['ret_msg']) # Call the error method to see if the call failed elif result.is_error(): print('Error calling MobileApi.MobilePrepay') errors = result.errors # An error is returned as a list of errors for error in errors: # Each error is represented as a dictionary for key, value in error.items(): print(f"{key} : {value}") print("\n") ### 4. Data Search API # Get an instance of the Yuansfer Data Search API you want call api_data_search = client.data_search # Set request payload params = { "transactionNo": "297553638301777927" } # Make a Yuansfer Transaction Query request result = api_data_search.tran_query(params) # Call the success method to see if the call succeeded if result.is_success(): # Check if the request is successful if result.body['ret_code'] == '000100': # The body property is the resposne from Yuansfer yuansferResponse = result.body['result'] print(yuansferResponse) else: print(result.body['ret_msg']) # Call the error method to see if the call failed elif result.is_error(): print('Error calling DataSearchApi.TranQuery') errors = result.errors # An error is returned as a list of errors for error in errors: # Each error is represented as a dictionary for key, value in error.items(): print(f"{key} : {value}") print("\n") ### 5. PayPal Subscription API # Get an instance of the Pockyt Data Search API you want call api_recurring = client.recurring ## Set request payload # Declare PayPal Billing Cycle Object paypalBillingCycle = PayPalBillingCycle() paypalBillingCycle.sequence = 1 paypalBillingCycle.tenure_type = "REGULAR" paypalBillingCycle.total_cycles = 999 paypalBillingCycle.frequency = PayPalBillingCycleFrequency() paypalBillingCycle.frequency.interval_count = 1 paypalBillingCycle.frequency.interval_unit = "MONTH" paypalBillingCycle.pricing_scheme = PayPalBillingCyclePricingScheme() paypalBillingCycle.pricing_scheme.fixed_price = PayPalBillingCycleAmount() paypalBillingCycle.pricing_scheme.fixed_price.value = 20 paypalBillingCycle.pricing_scheme.fixed_price.currency_code = "USD" # Declare PayPal Payment Preferences Object paypalPaymentPreferences = PayPalPaymentPreferences() paypalPaymentPreferences.auto_bill_outstanding = True paypalPaymentPreferences.setup_fee = PayPalPaymentPreferencesSetUpFee() paypalPaymentPreferences.setup_fee.value = 20 paypalPaymentPreferences.setup_fee.currency_code = "USD" paypalPaymentPreferences.setup_fee_failure_action = "CONTINUE" paypalPaymentPreferences.Payment_failure_threshold = 3 # Declare PayPal Taxes Object paypalTaxes = PayPalTaxes() paypalTaxes.percentage = "10" paypalTaxes.inclusive = True # Declare PayPal Product Schema Object payPalProductSchema = PayPalProductSchema() payPalProductSchema.type = "SERVICE" payPalProductSchema.category = "SOFTWARE" params = { "clientId": "<MerchantPayPalClientID>", "secret": "<MerchantPayPalSecretID>", 'amount': "100", "productName": "descriptive name for product test", "planName": "descriptive name for plan test", "planDescription": "detailed description for plan", "requestIdProduct": "unique Id for create product request_, "requestIdPlan": "unique Id for create plan request", "frequency": "MONTH", "billingCycles": json.dumps([paypalBillingCycle] ), "paymentPreferences": json.dumps( paypalPaymentPreferences ), "taxes": json.dumps( paypalTaxes ), "productSchema": json.dumps(payPalProductSchema) } # Make a Pockyt PayPal Subscription request result = api_recurring.paypal_subscription(params) # Call the success method to see if the call succeeded if result.is_success(): # Check if the request is successful if result.body['ret_code'] == '000100': # The body property is the response from Pockyt yuansferResponse = result.body['result'] print(yuansferResponse) else: print(result.body['ret_msg']) # Call the error method to see if the call failed elif result.is_error(): print('Error calling RecurringApi.PayPal_Subscription') errors = result.errors # An error is returned as a list of errors for error in errors: # Each error is represented as a dictionary for key, value in error.items(): print(f"{key} : {value}") print("\n")
yuansfer
/yuansfer-3.0.4.tar.gz/yuansfer-3.0.4/README.md
README.md
from distutils import log from distutils.core import Command from distutils.errors import DistutilsSetupError import os import re from datetime import date class release(Command): description = "create and release a new version" user_options = [ ('keyid', None, "GPG key to sign with"), ('skip-tests', None, "skip running the tests"), ('pypi', None, "publish to pypi"), ] boolean_options = ['skip-tests', 'pypi'] def initialize_options(self): self.keyid = None self.skip_tests = 0 self.pypi = 0 def finalize_options(self): self.cwd = os.getcwd() self.fullname = self.distribution.get_fullname() self.name = self.distribution.get_name() self.version = self.distribution.get_version() def _verify_version(self): with open('NEWS', 'r') as news_file: line = news_file.readline() now = date.today().strftime('%Y-%m-%d') if not re.search(r'Version %s \(released %s\)' % (self.version, now), line): raise DistutilsSetupError("Incorrect date/version in NEWS!") def _verify_tag(self): if os.system('git tag | grep -q "^%s\$"' % self.fullname) == 0: raise DistutilsSetupError( "Tag '%s' already exists!" % self.fullname) def _sign(self): if os.path.isfile('dist/%s.tar.gz.asc' % self.fullname): # Signature exists from upload, re-use it: sign_opts = ['--output dist/%s.tar.gz.sig' % self.fullname, '--dearmor dist/%s.tar.gz.asc' % self.fullname] else: # No signature, create it: sign_opts = ['--detach-sign', 'dist/%s.tar.gz' % self.fullname] if self.keyid: sign_opts.insert(1, '--default-key ' + self.keyid) self.execute(os.system, ('gpg ' + (' '.join(sign_opts)),)) if os.system('gpg --verify dist/%s.tar.gz.sig' % self.fullname) != 0: raise DistutilsSetupError("Error verifying signature!") def _tag(self): tag_opts = ['-s', '-m ' + self.fullname, self.fullname] if self.keyid: tag_opts[0] = '-u ' + self.keyid self.execute(os.system, ('git tag ' + (' '.join(tag_opts)),)) def _do_call_publish(self, cmd): self._published = os.system(cmd) == 0 def _publish(self): web_repo = os.getenv('YUBICO_GITHUB_REPO') if web_repo and os.path.isdir(web_repo): artifacts = [ 'dist/%s.tar.gz' % self.fullname, 'dist/%s.tar.gz.sig' % self.fullname ] cmd = '%s/publish %s %s %s' % ( web_repo, self.name, self.version, ' '.join(artifacts)) self.execute(self._do_call_publish, (cmd,)) if self._published: self.announce("Release published! Don't forget to:", log.INFO) self.announce("") self.announce(" (cd %s && git push)" % web_repo, log.INFO) self.announce("") else: self.warn("There was a problem publishing the release!") else: self.warn("YUBICO_GITHUB_REPO not set or invalid!") self.warn("This release will not be published!") def run(self): if os.getcwd() != self.cwd: raise DistutilsSetupError("Must be in package root!") self._verify_version() self._verify_tag() self.execute(os.system, ('git2cl > ChangeLog',)) if not self.skip_tests: self.run_command('check') # Nosetests calls sys.exit(status) try: self.run_command('nosetests') except SystemExit as e: if e.code != 0: raise DistutilsSetupError("There were test failures!") self.run_command('sdist') if self.pypi: cmd_obj = self.distribution.get_command_obj('upload') cmd_obj.sign = True if self.keyid: cmd_obj.identity = self.keyid self.run_command('upload') self._sign() self._tag() self._publish() self.announce("Release complete! Don't forget to:", log.INFO) self.announce("") self.announce(" git push && git push --tags", log.INFO) self.announce("")
yubiadmin
/yubiadmin-0.1.7.tar.gz/yubiadmin-0.1.7/release.py
release.py
from distutils import log from distutils.core import Command from distutils.errors import DistutilsSetupError import os import re from datetime import date class release(Command): description = "create and release a new version" user_options = [ ('keyid', None, "GPG key to sign with"), ('skip-tests', None, "skip running the tests"), ('pypi', None, "publish to pypi"), ] boolean_options = ['skip-tests', 'pypi'] def initialize_options(self): self.keyid = None self.skip_tests = 0 self.pypi = 0 def finalize_options(self): self.cwd = os.getcwd() self.fullname = self.distribution.get_fullname() self.name = self.distribution.get_name() self.version = self.distribution.get_version() def _verify_version(self): with open('NEWS', 'r') as news_file: line = news_file.readline() now = date.today().strftime('%Y-%m-%d') if not re.search(r'Version %s \(released %s\)' % (self.version, now), line): raise DistutilsSetupError("Incorrect date/version in NEWS!") def _verify_tag(self): if os.system('git tag | grep -q "^%s\$"' % self.fullname) == 0: raise DistutilsSetupError( "Tag '%s' already exists!" % self.fullname) def _sign(self): if os.path.isfile('dist/%s.tar.gz.asc' % self.fullname): # Signature exists from upload, re-use it: sign_opts = ['--output dist/%s.tar.gz.sig' % self.fullname, '--dearmor dist/%s.tar.gz.asc' % self.fullname] else: # No signature, create it: sign_opts = ['--detach-sign', 'dist/%s.tar.gz' % self.fullname] if self.keyid: sign_opts.insert(1, '--default-key ' + self.keyid) self.execute(os.system, ('gpg ' + (' '.join(sign_opts)),)) if os.system('gpg --verify dist/%s.tar.gz.sig' % self.fullname) != 0: raise DistutilsSetupError("Error verifying signature!") def _tag(self): tag_opts = ['-s', '-m ' + self.fullname, self.fullname] if self.keyid: tag_opts[0] = '-u ' + self.keyid self.execute(os.system, ('git tag ' + (' '.join(tag_opts)),)) def _do_call_publish(self, cmd): self._published = os.system(cmd) == 0 def _publish(self): web_repo = os.getenv('YUBICO_GITHUB_REPO') if web_repo and os.path.isdir(web_repo): artifacts = [ 'dist/%s.tar.gz' % self.fullname, 'dist/%s.tar.gz.sig' % self.fullname ] cmd = '%s/publish %s %s %s' % ( web_repo, self.name, self.version, ' '.join(artifacts)) self.execute(self._do_call_publish, (cmd,)) if self._published: self.announce("Release published! Don't forget to:", log.INFO) self.announce("") self.announce(" (cd %s && git push)" % web_repo, log.INFO) self.announce("") else: self.warn("There was a problem publishing the release!") else: self.warn("YUBICO_GITHUB_REPO not set or invalid!") self.warn("This release will not be published!") def run(self): if os.getcwd() != self.cwd: raise DistutilsSetupError("Must be in package root!") self._verify_version() self._verify_tag() self.execute(os.system, ('git2cl > ChangeLog',)) if not self.skip_tests: self.run_command('check') # Nosetests calls sys.exit(status) try: self.run_command('nosetests') except SystemExit as e: if e.code != 0: raise DistutilsSetupError("There were test failures!") self.run_command('sdist') if self.pypi: cmd_obj = self.distribution.get_command_obj('upload') cmd_obj.sign = True if self.keyid: cmd_obj.identity = self.keyid self.run_command('upload') self._sign() self._tag() self._publish() self.announce("Release complete! Don't forget to:", log.INFO) self.announce("") self.announce(" git push && git push --tags", log.INFO) self.announce("")
yubiauth
/yubiauth-0.3.10.tar.gz/yubiauth-0.3.10/release.py
release.py
# # This is a working example of using a YubiAuth backend to validate HTTP BASIC # AUTH user authentication. It can be used, for example, by mod_wsgi to add # authetication to a WSGI application. # # YubiKey OTPs are expected to be appended to either the username or password. # import re import base64 import requests OTP_PATTERN = re.compile(r'^(.*)([cbdefghijklnrtuv]{44})$') def parse_auth(auth): username, password = base64.b64decode(auth).split(':', 1) username_match = OTP_PATTERN.match(username) if username_match: username = username_match.group(1) otp = username_match.group(2) else: password_match = OTP_PATTERN.match(password) if password_match: password = password_match.group(1) otp = password_match.group(2) else: otp = None return username, password, otp class YubiAuthValidator(object): """ Validates HTTP BASIC authentication credentials using a YubiAuth backend. HTTP BASIC sends the credentials for each request. Initially we parse the username, password and (optionally) OTP and create a user session. On subsequent requests, we use the auth string as a key to lookup the session key and validate the session. Example: validator = YubiAuthValidator() if validator(auth): print 'Validation OK!' """ def __init__(self, url='http://127.0.0.1/yubiauth/client'): self.base_url = url self.sessions = {} def __call__(self, auth): """ Call with the Base64 encoded auth string from the request. Returns True on successful authentication, else False. """ if auth in self.sessions: return self.validate_session(auth) return self.create_session(auth) def create_session(self, auth): username, password, otp = parse_auth(auth) if not self.validate_user(username): return False url = '%s/login' % self.base_url response = requests.post(url, data={ 'username': username, 'password': password, 'otp': otp}) if response.status_code == requests.codes.ok: self.sessions[auth] = response.cookies['YubiAuth-Session'] return True return False def validate_user(self, username): """ Override this to return False if the given user shouldn't be granted access. """ return True def validate_session(self, auth): if auth in self.sessions: session_id = self.sessions[auth] url = '%s/status' % self.base_url response = requests.get(url, cookies={'YubiAuth-Session': session_id}) if response.status_code == requests.codes.ok: return True del self.sessions[auth] return False validator = YubiAuthValidator() # check_password function for use with mod_wsgi. To use, add this to your # Apache configuration. # # AuthType Basic # AuthName "YubiAuth" # AuthBasicProvider wsgi # WSGIAuthUserScript /path/to/http_basic_auth.py # Require valid-user def check_password(environ, user, password): # mod_wsgi has already unpacked the username and password, # but we expect them to be packed, so re-pack: return validator(base64.b64encode('%s:%s' % (user, password)))
yubiauth
/yubiauth-0.3.10.tar.gz/yubiauth-0.3.10/examples/http_basic_auth.py
http_basic_auth.py
from distutils import log from distutils.core import Command from distutils.errors import DistutilsSetupError import os import re from datetime import date class release(Command): description = "create and release a new version" user_options = [ ('keyid', None, "GPG key to sign with"), ('skip-tests', None, "skip running the tests"), ('pypi', None, "publish to pypi"), ] boolean_options = ['skip-tests', 'pypi'] def initialize_options(self): self.keyid = None self.skip_tests = 0 self.pypi = 0 def finalize_options(self): self.cwd = os.getcwd() self.fullname = self.distribution.get_fullname() self.name = self.distribution.get_name() self.version = self.distribution.get_version() def _verify_version(self): with open('NEWS', 'r') as news_file: line = news_file.readline() now = date.today().strftime('%Y-%m-%d') if not re.search(r'Version %s \(released %s\)' % (self.version, now), line): raise DistutilsSetupError("Incorrect date/version in NEWS!") def _verify_tag(self): if os.system('git tag | grep -q "^%s\$"' % self.fullname) == 0: raise DistutilsSetupError( "Tag '%s' already exists!" % self.fullname) def _sign(self): if os.path.isfile('dist/%s.tar.gz.asc' % self.fullname): # Signature exists from upload, re-use it: sign_opts = ['--output dist/%s.tar.gz.sig' % self.fullname, '--dearmor dist/%s.tar.gz.asc' % self.fullname] else: # No signature, create it: sign_opts = ['--detach-sign', 'dist/%s.tar.gz' % self.fullname] if self.keyid: sign_opts.insert(1, '--default-key ' + self.keyid) self.execute(os.system, ('gpg ' + (' '.join(sign_opts)),)) if os.system('gpg --verify dist/%s.tar.gz.sig' % self.fullname) != 0: raise DistutilsSetupError("Error verifying signature!") def _tag(self): tag_opts = ['-s', '-m ' + self.fullname, self.fullname] if self.keyid: tag_opts[0] = '-u ' + self.keyid self.execute(os.system, ('git tag ' + (' '.join(tag_opts)),)) def _do_call_publish(self, cmd): self._published = os.system(cmd) == 0 def _publish(self): web_repo = os.getenv('YUBICO_GITHUB_REPO') if web_repo and os.path.isdir(web_repo): artifacts = [ 'dist/%s.tar.gz' % self.fullname, 'dist/%s.tar.gz.sig' % self.fullname ] cmd = '%s/publish %s %s %s' % ( web_repo, self.name, self.version, ' '.join(artifacts)) self.execute(self._do_call_publish, (cmd,)) if self._published: self.announce("Release published! Don't forget to:", log.INFO) self.announce("") self.announce(" (cd %s && git push)" % web_repo, log.INFO) self.announce("") else: self.warn("There was a problem publishing the release!") else: self.warn("YUBICO_GITHUB_REPO not set or invalid!") self.warn("This release will not be published!") def run(self): if os.getcwd() != self.cwd: raise DistutilsSetupError("Must be in package root!") self._verify_version() self._verify_tag() self.execute(os.system, ('git2cl > ChangeLog',)) if not self.skip_tests: self.run_command('check') # Nosetests calls sys.exit(status) try: self.run_command('nosetests') except SystemExit as e: if e.code != 0: raise DistutilsSetupError("There were test failures!") self.run_command('sdist') if self.pypi: cmd_obj = self.distribution.get_command_obj('upload') cmd_obj.sign = True if self.keyid: cmd_obj.identity = self.keyid self.run_command('upload') self._sign() self._tag() self._publish() self.announce("Release complete! Don't forget to:", log.INFO) self.announce("") self.announce(" git push && git push --tags", log.INFO) self.announce("")
yubico-bitcoin
/yubico-bitcoin-0.0.1.tar.gz/yubico-bitcoin-0.0.1/release.py
release.py
import struct import re from smartcard.System import readers from yubico_bitcoin.exc import (NoKeyLoadedException, PINModeLockedException, IncorrectPINException) __all__ = [ 'open_key', 'YkneoBitcoin' ] READER_PATTERN = re.compile('.*Yubikey NEO.*') def require_user(orig): def new_func(neo, *args, **kwargs): if not neo.user_unlocked: raise PINModeLockedException(False) return orig(neo, *args, **kwargs) return new_func def require_admin(orig): def new_func(neo, *args, **kwargs): if not neo.admin_unlocked: raise PINModeLockedException(True) return orig(neo, *args, **kwargs) return new_func def require_key(orig): def new_func(neo, *args, **kwargs): if not neo.key_loaded: raise NoKeyLoadedException() return orig(neo, *args, **kwargs) return new_func def hex2cmd(data): return map(ord, data.decode('hex')) def pack_path(path): return ''.join([struct.pack('>I', index) for index in [int(i[:-1]) | 0x80000000 if i.endswith("'") else int(i) for i in path.split('/')]]) def open_key(name=None): """ Opens a smartcard reader matching the given name and connects to the ykneo-bitcoin applet through it. Returns a reference to the YkneoBitcoin object. """ r = re.compile(name) if name else READER_PATTERN for reader in readers(): if r.match(reader.name): conn = reader.createConnection() conn.connect() return YkneoBitcoin(conn) raise Exception('No smartcard reader found matching: %s' % r.pattern) class YkneoBitcoin(object): """ Interface to the ykneo-bitcoin applet running on a YubiKey NEO. Extended keys used are in the <a href="https://en.bitcoin.it/wiki/BIP_0032">BIP 32</a> format. A single extended key pair is stored on the YubiKey NEO, which is used to derive sub keys used for signing. BIP 32 supports a tree hierarchy of keys, and ykneo-bitcoin supports accessing these sub keys for use in the get_public_key and sign methods. Private key derivation is supported, by setting the first (sign-) bit of index, as per the BIP 32 specification. Example: neo = new YkneoBitcoin(...) master_key = ... neo.import_extended_key_pair(master_key, False) # neo now holds the master key pair m. # This returns the uncompressed public key from sub key m/0/7: neo.get_public_key(0, 7) # This returns the signature of hash signed by m/1/4711': neo.sign(1, 4711 | 0x80000000, hash) """ def __init__(self, reader): self.reader = reader self._user_unlocked = False self._admin_unlocked = False data, status = self._cmd(0, 0xa4, 0x04, 0x00, 'a0000005272102'.decode('hex')) if (status) != 0x9000: raise Exception('Unable to select the applet') self._version = tuple(data[0:3]) self._key_loaded = data[3] == 1 @property def user_unlocked(self): return self._user_unlocked @property def admin_unlocked(self): return self._admin_unlocked @property def version(self): return "%d.%d.%d" % self._version @property def key_loaded(self): return self._key_loaded def _cmd(self, cl, ins, p1, p2, data=''): command = '%02x%02x%02x%02x%02x%s' % (cl, ins, p1, p2, len(data), data.encode('hex')) data, sw1, sw2 = self.reader.transmit(hex2cmd(command)) return data, sw1 << 8 | sw2 def _cmd_ok(self, *args, **kwargs): data, status = self._cmd(*args, **kwargs) if status != 0x9000: raise Exception('APDU error: 0x%04x' % status) return ''.join(map(chr, data)) def unlock_user(self, pin): _, status = self._cmd(0, 0x21, 0, 0, pin) if status == 0x9000: self._user_unlocked = True elif status & 0xfff0 == 0x63c0: self._user_unlocked = False raise IncorrectPINException(False, status & 0xf) else: raise Exception('APDU error: 0x%04x' % status) def unlock_admin(self, pin): _, status = self._cmd(0, 0x21, 0, 1, pin) if status == 0x9000: self._admin_unlocked = True elif status & 0xfff0 == 0x63c0: self._admin_unlocked = False raise IncorrectPINException(True, status & 0xf) else: raise Exception('APDU error: 0x%04x' % status) def _send_set_pin(self, old_pin, new_pin, admin): data = chr(len(old_pin)) + old_pin + chr(len(new_pin)) + new_pin _, status = self._cmd(0, 0x22, 0, 1 if admin else 0, data) return status def set_admin_pin(self, old_pin, new_pin): status = self._send_set_pin(old_pin, new_pin, True) if status == 0x9000: self._admin_unlocked = True elif status & 0xfff0 == 0x63c0: self._admin_unlocked = False raise IncorrectPINException(True, status & 0xf) else: raise Exception('APDU error: 0x%04x' % status) def set_user_pin(self, old_pin, new_pin): status = self._send_set_pin(old_pin, new_pin, False) if status == 0x9000: self._user_unlocked = True elif status & 0xfff0 == 0x63c0: self._user_unlocked = False raise IncorrectPINException(False, status & 0xf) else: raise Exception('APDU error: 0x%04x' % status) @require_admin def _send_set_retry_count(self, attempts, admin): if not 0 < attempts < 16: raise ValueError('Attempts must be 1-15, was: %d', attempts) self._cmd_ok(0, 0x15, 0, 1 if admin else 0, chr(attempts)) def set_user_retry_count(self, attempts): self._send_set_retry_count(attempts, False) def set_admin_retry_count(self, attempts): self._send_set_retry_count(attempts, True) @require_admin def reset_user_pin(self, pin): self._cmd_ok(0, 0x14, 0, 0, pin) @require_admin def generate_master_key_pair(self, allow_export, return_private, testnet=False): p2 = 0 if allow_export: p2 |= 0x01 if return_private: p2 |= 0x02 if testnet: p2 |= 0x04 resp = self._cmd_ok(0, 0x11, 0, p2) self._key_loaded = True return resp @require_admin def import_extended_key_pair(self, serialized_key, allow_export): self._cmd_ok(0, 0x12, 0, 1 if allow_export else 0, serialized_key) self._key_loaded = True @require_admin def export_extended_public_key(self): return self._cmd_ok(0, 0x13, 0, 0) @require_user @require_key def get_public_key(self, path): return self._cmd_ok(0, 0x01, 0, 0, pack_path(path)) @require_user @require_key def sign(self, path, digest): if len(digest) != 32: raise ValueError('Digest must be 32 bytes') return self._cmd_ok(0, 0x02, 0, 0, pack_path(path) + digest) @require_user @require_key def get_header(self): return self._cmd_ok(0, 0x03, 0, 0)
yubico-bitcoin
/yubico-bitcoin-0.0.1.tar.gz/yubico-bitcoin-0.0.1/yubico_bitcoin/ykneo.py
ykneo.py
.. :changelog: Changelog ========= 1.13.0 - 2020-05-21 ------------------- * Update client to query a single API server instead of multiple ones in parallel by default. Previously, we queried 6 Yubico API servers in parallel for high availability and performance reasons. Now api.yubico.com is globally distributed and load balanced so there is no need for us to do that anymore and we can just query a single API server and let the server handle HA and load-balancing. Users who run their own internal Yubikey validation servers can still specify a list of servers by passing ``api_urls`` argument to the client constructor (same as before). Contributed by @mallensb and @nrw505. Part of #31 and #32. 1.12.0 - 2019-11-18 ------------------- * Update code to retry HTTP requests for server errors which might work on a retry (5xx status codes returned by the server). Those errors could simply indicate a gateway or a proxy error which might work on a retry. Contributed by Nigel Williams (@nrw505) #30 * Pin minimum version for ``requests`` dependency to ``v2.22.0``. * Update the code so we don't throw an exception if one of the multiple servers we query has issues. We query multiple servers in parallel purely for availability reasons and the consistency / sync part is taken care by the server side. The client returns immediately as soon as it receives one positive or a negative response. Contributed by Nigel Williams (@nrw505) #29 * Update code so we send ``User-Agent`` header which includes client version information and platform string with each HTTP request. * Also test the code with Python 3.8.0 and indicate we also support Python 3.8. 1.11.0 - 2019-07-06 ------------------- * Drop support for Python 2.6. #28 * Test the code and verify it works with the following Python versions: * Python 3.3 * Python 3.4 * Python 3.5 * Python 3.6 * Python 3.7 * PyPy 2 * PyPy 3 #28 1.10.0 - 2015-10-02 ------------------- * Fix compatibility issue with Python versions >= 3.0 <= 3.3 #22 * Pin ``requests`` dependency to the latest version (2.7) #25 #27 Contribution by Wouter van Bommel, Vianney Carel. * Make sure the query parameters are unquoted when parsing them from the response. #23 Contribution by Tamás Gulácsi. 1.9.1 - 2014-02-05 ------------------ * Fix Python 3 compatibility issue. #21 1.9.0 - 2014-01-16 ------------------ * To discourage bad practices, remove ``use_https`` argument from the `Yubico` class constructor all together. Also update ``DEFAULT_API_URLS`` variable to contain full URLs with a scheme (e.g. ``https://api.yubico.com/wsapi/2.0/verify``). If a user wants to use a custom non-https URL or URLs, they can still do that by passing ``api_urls`` argument with custom non-https URLs to the constructor. * Replace ``CA_CERTS_BUNDLE_PATH`` module level variable with a ``ca_certs_bundle_path`` argument which can be passed to the Yubico class constructor. * Update ``requests`` dependency from ``1.2`` to ``2.2``. 1.8.0 - 2013-11-09 ------------------ * Modify ``verify_multi`` method to throw if ``otp_list`` argument contains less than two items * Modify ``max_time_window`` argument in the ``verify_multi`` method to be in seconds (#19) * Modify ``verify_multi`` method to throw if delta between the first and last OTP timestamp is smaller than zero * Allow user to pass ``api_urls`` argument to the ``Yubico`` class constructor. This argument can contain a list of API urls which are used to validate the token. https://github.com/Kami/python-yubico-client/pull/18 Contributed by Dain Nilsson * Depend on newer version (``1.2.3``) of the ``requests`` library. * Update code and tests so they also work under Python 3.3 1.7.0 - 2013-04-06 ------------------ * Change PyPi package name from ``yubico`` to ``yubico-client``. This was done to prevent naming collisions and make creation of distribution specific packages (e.g. debian packages) easier. 1.6.2 - 2013-04-02 ------------------ * If there are multiple interpretations for a given OTP, first try to find the one which matches the input OTP. If the one is found, use the input OTP, otherwise use random interpretation. - https://github.com/Kami/python-yubico-client/issues/14 Reported by Klas Lindfors 1.6.1 - 2013-03-19 ------------------ * Only run ``logging.basicConfig`` when running tests so logging config isn't initialised on module import - https://github.com/Kami/python-yubico-client/pull/13 1.6.0 - 2013-01-24 ------------------ * Allow user to specify a path to the CA bundle which is used for verifying the server SSL certificate by setting ``CA_CERTS_BUNDLE_PATH`` variable. * When selecting which CA bundle is used for verifying the server SSL certificate look for the bundle in some common locations - https://github.com/Kami/python-yubico-client/pull/10 * Drop support for Python 2.5 * Use ``requests`` library for performing HTTP requests and turn SSL cert verification on by default * Avoid busy-looping (add ``time.sleep``) when waiting for responses - https://github.com/Kami/python-yubico-client/pull/9 * Allow user to pass in value ``0`` for ``sl`` argument in ``verify`` and ``verify_multi`` method - https://github.com/Kami/python-yubico-client/pull/8 * Throw an exception inside ``verify`` and ``verify_multi`` method if timeout has occurred or invalid status code is returned - https://github.com/Kami/python-yubico-client/pull/7 * Improve response validation and of included, verify that ``otp`` and ``nonce`` parameters in the response match one provided in the request - https://github.com/Kami/python-yubico-client/pull/7 * Add logging
yubico-client
/yubico-client-1.13.0.tar.gz/yubico-client-1.13.0/CHANGES.rst
CHANGES.rst
Yubico Python Client ==================== .. image:: https://img.shields.io/pypi/v/yubico-client.svg :target: https://pypi.python.org/pypi/yubico-client/ .. image:: https://img.shields.io/pypi/dm/yubico-client.svg :target: https://pypi.python.org/pypi/yubico-client/ .. image:: https://secure.travis-ci.org/Kami/python-yubico-client.png?branch=master :target: http://travis-ci.org/Kami/python-yubico-client .. image:: https://img.shields.io/codecov/c/github/Kami/python-yubico-client/master.svg :target: https://codecov.io/github/Kami/python-yubico-client?branch=master .. image:: https://img.shields.io/pypi/pyversions/yubico-client.svg :target: https://pypi.python.org/pypi/yubico-client/ .. image:: https://img.shields.io/pypi/wheel/yubico-client.svg :target: https://pypi.python.org/pypi/yubico-client/ .. image:: https://img.shields.io/github/license/Kami/python-yubico-client.svg :target: https://github.com/Kami/python-yubico-client/blob/trunk/LICENSE Python class for verifying Yubico One Time Passwords (OTPs) based on the validation protocol version 2.0. * Yubico website: http://www.yubico.com * Yubico documentation: http://www.yubico.com/developers/intro/ * Validation Protocol Version 2.0 description: https://developers.yubico.com/yubikey-val/Validation_Protocol_V2.0.html For more information and usage examples, please see the. `documentation <https://yubico-client.readthedocs.org/en/latest/>`_. Documentation ------------- Documentation is available at https://yubico-client.readthedocs.org/en/latest/ Installation ------------ .. code-block:: bash $ pip install yubico-client Note: Package has been recently renamed from `yubico` to `yubico-client` and the main module has been renamed from `yubico` to `yubico_client`. This was done to avoid naming conflicts and make creation of distribution specific packages easier. Supported Python Versions ------------------------- * Python 2.7 * Python 3.4 * Python 3.5 * Python 3.6 * Python 3.7 * Python 3.8 * PyPy 2 * PyPy 3 Running Tests ------------- To run the tests use the tox command. This will automatically run the tests on all the supported Python versions. .. code-block:: bash $ tox License ------- Yubico Client is distributed under the `3-Clause BSD License`_. .. _`3-Clause BSD License`: http://opensource.org/licenses/BSD-3-Clause
yubico-client
/yubico-client-1.13.0.tar.gz/yubico-client-1.13.0/README.rst
README.rst
import re import os import sys import time import hmac import base64 import hashlib import threading import logging import requests from yubico_client import __version__ from yubico_client.otp import OTP from yubico_client.yubico_exceptions import (StatusCodeError, InvalidClientIdError, InvalidValidationResponse, SignatureVerificationError) from yubico_client.py3 import b from yubico_client.py3 import urlencode from yubico_client.py3 import unquote logger = logging.getLogger('yubico.client') # Path to the standard CA bundle file locations for most of the operating # systems COMMON_CA_LOCATIONS = [ '/usr/local/lib/ssl/certs/ca-certificates.crt', '/usr/local/ssl/certs/ca-certificates.crt', '/usr/local/share/curl/curl-ca-bundle.crt', '/usr/local/etc/openssl/cert.pem', '/opt/local/lib/ssl/certs/ca-certificates.crt', '/opt/local/ssl/certs/ca-certificates.crt', '/opt/local/share/curl/curl-ca-bundle.crt', '/opt/local/etc/openssl/cert.pem', '/usr/lib/ssl/certs/ca-certificates.crt', '/usr/ssl/certs/ca-certificates.crt', '/usr/share/curl/curl-ca-bundle.crt', '/etc/ssl/certs/ca-certificates.crt', '/etc/pki/tls/cert.pem', '/etc/pki/CA/cacert.pem', r'C:\Windows\curl-ca-bundle.crt', r'C:\Windows\ca-bundle.crt', r'C:\Windows\cacert.pem' ] DEFAULT_API_URLS = ('https://api.yubico.com/wsapi/2.0/verify',) # How long to wait before the time out occurs DEFAULT_TIMEOUT = 10 # How many seconds can pass between the first and last OTP generation so the # OTP is still considered valid DEFAULT_MAX_TIME_WINDOW = 5 BAD_STATUS_CODES = ['BAD_OTP', 'REPLAYED_OTP', 'BAD_SIGNATURE', 'MISSING_PARAMETER', 'OPERATION_NOT_ALLOWED', 'BACKEND_ERROR', 'NOT_ENOUGH_ANSWERS', 'REPLAYED_REQUEST'] CLIENT_VERSION = '.'.join([str(part) for part in __version__]) PYTHON_VERSION = '%s.%s.%s' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) class Yubico(object): # pylint: disable=too-many-instance-attributes def __init__(self, client_id, key=None, verify_cert=True, translate_otp=True, api_urls=DEFAULT_API_URLS, ca_certs_bundle_path=None, max_retries=3, retry_delay=0.5): """ :param max_retries: Number of times to try to retry the request if server returns 5xx status code. :type max_retries: ``int`` :param retry_delay: How long to wait (in seconds) beteween each retry attempt. :param retry_delay: ``float`` """ if ca_certs_bundle_path and \ not self._is_valid_ca_bundle_file(ca_certs_bundle_path): raise ValueError('Invalid value provided for ca_certs_bundle_path' ' argument') self.client_id = client_id if key is not None: key = base64.b64decode(key.encode('ascii')) self.key = key self.verify_cert = verify_cert self.translate_otp = translate_otp self.api_urls = self._init_request_urls(api_urls=api_urls) self.ca_certs_bundle_path = ca_certs_bundle_path self.max_retries = max_retries self.retry_delay = retry_delay def verify(self, otp, timestamp=False, sl=None, timeout=None, return_response=False): """ Verify a provided OTP. :param otp: OTP to verify. :type otp: ``str`` :param timestamp: True to include request timestamp and session counter in the response. Defaults to False. :type timestamp: ``bool`` :param sl: A value indicating percentage of syncing required by client. :type sl: ``int`` or ``str`` :param timeout: Number of seconds to wait for sync responses. :type timeout: ``int`` :param return_response: True to return a response object instead of the status code. Defaults to False. :type return_response: ``bool`` :return: True is the provided OTP is valid, False if the REPLAYED_OTP status value is returned or the response message signature verification failed and None for the rest of the status values. """ ca_bundle_path = self._get_ca_bundle_path() otp = OTP(otp, self.translate_otp) rand_str = b(os.urandom(30)) nonce = base64.b64encode(rand_str, b('xz'))[:25].decode('utf-8') query_string = self.generate_query_string(otp.otp, nonce, timestamp, sl, timeout) threads = [] timeout = timeout or DEFAULT_TIMEOUT for url in self.api_urls: thread = URLThread(url='%s?%s' % (url, query_string), timeout=timeout, verify_cert=self.verify_cert, ca_bundle_path=ca_bundle_path, max_retries=self.max_retries, retry_delay=self.retry_delay) thread.start() threads.append(thread) # Wait for a first positive or negative response start_time = time.time() # If there's only one server to talk to, raise thread exceptions. # Otherwise we end up ignoring a good answer from a different # server later. raise_exceptions = (len(threads) == 1) # pylint: disable=too-many-nested-blocks while threads and (start_time + timeout) > time.time(): for thread in threads: if not thread.is_alive(): if thread.exception and raise_exceptions: raise thread.exception elif thread.response: status = self.verify_response(thread.response, otp.otp, nonce, return_response) if status: # pylint: disable=no-else-return if return_response: return status else: return True threads.remove(thread) time.sleep(0.1) # Timeout or no valid response received raise Exception('NO_VALID_ANSWERS') def verify_multi(self, otp_list, max_time_window=DEFAULT_MAX_TIME_WINDOW, sl=None, timeout=None): """ Verify a provided list of OTPs. :param max_time_window: Maximum number of seconds which can pass between the first and last OTP generation for the OTP to still be considered valid. :type max_time_window: ``int`` """ # Create the OTP objects otps = [] for otp in otp_list: otps.append(OTP(otp, self.translate_otp)) if len(otp_list) < 2: raise ValueError('otp_list needs to contain at least two OTPs') device_ids = set() for otp in otps: device_ids.add(otp.device_id) # Check that all the OTPs contain same device id if len(device_ids) != 1: raise Exception('OTPs contain different device ids') # Now we verify the OTPs and save the server response for each OTP. # We need the server response, to retrieve the timestamp. # It's possible to retrieve this value locally, without querying the # server but in this case, user would need to provide his AES key. for otp in otps: response = self.verify(otp.otp, True, sl, timeout, return_response=True) if not response: return False otp.timestamp = int(response['timestamp']) count = len(otps) delta = otps[count - 1].timestamp - otps[0].timestamp # OTPs have an 8Hz timestamp counter so we need to divide it to get # seconds delta = delta / 8 if delta < 0: raise Exception('delta is smaller than zero. First OTP appears to ' 'be older than the last one') if delta > max_time_window: raise Exception('More than %s seconds have passed between ' 'generating the first and the last OTP.' % (max_time_window)) return True def verify_response(self, response, otp, nonce, return_response=False): """ Returns True if the OTP is valid (status=OK) and return_response=False, otherwise (return_response = True) it returns the server response as a dictionary. Throws an exception if the OTP is replayed, the server response message verification failed or the client id is invalid, returns False otherwise. """ try: status = re.search(r'status=([A-Z0-9_]+)', response) \ .groups() if len(status) > 1: message = 'More than one status= returned. Possible attack!' raise InvalidValidationResponse(message, response) status = status[0] except (AttributeError, IndexError): return False signature, parameters = \ self.parse_parameters_from_response(response) # Secret key is specified, so we verify the response message # signature if self.key: generated_signature = \ self.generate_message_signature(parameters) # Signature located in the response does not match the one we # have generated if signature != generated_signature: logger.warning("signature mismatch for parameters=%r", parameters) raise SignatureVerificationError(generated_signature, signature) param_dict = self.get_parameters_as_dictionary(parameters) if 'otp' in param_dict and param_dict['otp'] != otp: message = 'Unexpected OTP in response. Possible attack!' raise InvalidValidationResponse(message, response, param_dict) if 'nonce' in param_dict and param_dict['nonce'] != nonce: message = 'Unexpected nonce in response. Possible attack!' raise InvalidValidationResponse(message, response, param_dict) if status == 'OK': if return_response: # pylint: disable=no-else-return return param_dict else: return True elif status == 'NO_SUCH_CLIENT': raise InvalidClientIdError(self.client_id) elif status == 'REPLAYED_OTP': raise StatusCodeError(status) return False def generate_query_string(self, otp, nonce, timestamp=False, sl=None, timeout=None): """ Returns a query string which is sent to the validation servers. """ data = [('id', self.client_id), ('otp', otp), ('nonce', nonce)] if timestamp: data.append(('timestamp', '1')) if sl is not None: if sl not in range(0, 101) and sl not in ['fast', 'secure']: raise Exception('sl parameter value must be between 0 and ' '100 or string "fast" or "secure"') data.append(('sl', sl)) if timeout: data.append(('timeout', timeout)) query_string = urlencode(data) if self.key: hmac_signature = self.generate_message_signature(query_string) query_string += '&h=%s' % (hmac_signature.replace('+', '%2B')) return query_string def generate_message_signature(self, query_string): """ Returns a HMAC-SHA-1 signature for the given query string. http://goo.gl/R4O0E """ # split for sorting pairs = query_string.split('&') pairs = [pair.split('=', 1) for pair in pairs] pairs_sorted = sorted(pairs) pairs_string = '&' . join(['=' . join(pair) for pair in pairs_sorted]) digest = hmac.new(self.key, b(pairs_string), hashlib.sha1).digest() signature = base64.b64encode(digest).decode('utf-8') return signature def parse_parameters_from_response(self, response): """ Returns a response signature and query string generated from the server response. 'h' aka signature argument is stripped from the returned query string. """ lines = response.splitlines() pairs = [line.strip().split('=', 1) for line in lines if '=' in line] pairs = sorted(pairs) signature = ([unquote(v) for k, v in pairs if k == 'h'] or [None])[0] # already quoted query_string = '&' . join([k + '=' + v for k, v in pairs if k != 'h']) return (signature, query_string) def get_parameters_as_dictionary(self, query_string): """ Returns query string parameters as a dictionary. """ pairs = (x.split('=', 1) for x in query_string.split('&')) return dict((k, unquote(v)) for k, v in pairs) def _init_request_urls(self, api_urls): """ Returns a list of the API URLs. """ if not isinstance(api_urls, (str, list, tuple)): raise TypeError('api_urls needs to be string or iterable!') if isinstance(api_urls, str): api_urls = (api_urls,) api_urls = list(api_urls) for url in api_urls: if not url.startswith('http://') and \ not url.startswith('https://'): raise ValueError('URL "%s" contains an invalid or missing' ' scheme' % (url)) return list(api_urls) def _get_ca_bundle_path(self): """ Return a path to the CA bundle which is used for verifying the hosts SSL certificate. """ if self.ca_certs_bundle_path: # User provided a custom path return self.ca_certs_bundle_path # Return first bundle which is available for file_path in COMMON_CA_LOCATIONS: if self._is_valid_ca_bundle_file(file_path=file_path): return file_path return None def _is_valid_ca_bundle_file(self, file_path): return os.path.exists(file_path) and os.path.isfile(file_path) class URLThread(threading.Thread): # pylint: disable=too-many-instance-attributes def __init__(self, url, timeout, verify_cert, ca_bundle_path=None, max_retries=3, retry_delay=0.5): super(URLThread, self).__init__() self.url = url self.timeout = timeout self.verify_cert = verify_cert self.ca_bundle_path = ca_bundle_path self.max_retries = max_retries self.retry_delay = retry_delay self.exception = None self.request = None self.response = None def run(self): logger.debug('Sending HTTP request to %s (thread=%s)' % (self.url, self.name)) verify = self.verify_cert if self.ca_bundle_path is not None: verify = self.ca_bundle_path logger.debug('Using custom CA bunde: %s' % (self.ca_bundle_path)) headers = { 'User-Agent': ('yubico-python-client/%s (Python v%s)' % (CLIENT_VERSION, PYTHON_VERSION)) } try: retry = 0 done = False while retry < self.max_retries and not done: retry += 1 self.request = requests.get( url=self.url, timeout=self.timeout, verify=verify, headers=headers ) status_code = self.request.status_code args = (status_code, self.url, self.name) logger.debug('HTTP %d from %s (thread=%s)' % (args)) if status_code in (500, 502, 503, 504): logger.debug('Retrying HTTP request (attempt_count=%s,' 'max_retries=%s)' % (retry, self.max_retries)) time.sleep(self.retry_delay) else: done = True self.response = self.request.content.decode("utf-8") except requests.exceptions.SSLError: e = sys.exc_info()[1] args = (self.url, self.name, str(e)) logger.error('SSL error talking to %s (thread=%s): %s' % (args)) self.exception = e self.response = None except Exception: # pylint: disable=broad-except e = sys.exc_info()[1] logger.error('Failed to retrieve response: %s' % (str(e))) self.response = None args = (self.url, self.name, self.response) logger.debug('Received response from %s (thread=%s): %s' % (args))
yubico-client
/yubico-client-1.13.0.tar.gz/yubico-client-1.13.0/yubico_client/yubico.py
yubico.py
# Yubico Python Client Python class for verifying Yubico One Time Passwords (OTPs) based on the validation protocol version 2.0. * Yubico website: [http://www.yubico.com][1] * Yubico documentation: [http://www.yubico.com/developers/intro/][2] * Validation Protocol Version 2.0 FAQ: [http://www.yubico.com/develop/open-source-software/web-api-clients/server/][3] * Validation Protocol Version 2.0 description: [https://github.com/Yubico/yubikey-val/wiki/ValidationProtocolV20][4] ## Installation `pip install yubico` ## Build Status [![Build Status](https://secure.travis-ci.org/Kami/python-yubico-client.png)](http://travis-ci.org/Kami/python-yubico-client) ## Running Tests `python setup.py test` ## Usage 1. Generate your client id and secret key (this can be done by visiting the [Yubico website](https://api.yubico.com/get-api-key/)) 2. Use the client Single mode: from yubico.yubico import Yubico yubico = Yubico('client id', 'secret key') yubico.verify('otp') Multi mode: from yubico.yubico import Yubico yubico = Yubico('client id', 'secret key') yubico.verify_multi(['otp 1', 'otp 2', 'otp 3']) The **verify** method will return `True` if the provided OTP is valid (STATUS=OK). The **verify_multi** method will return `True` if all of the provided OTPs are valid (STATUS=OK). Both methods can also throw one of the following exceptions: - **StatusCodeError** - server returned **REPLAYED_OTP** status code - **SignatureVerificationError** - server response message signature verification failed - **InvalidClientIdError** - client with the specified id does not exist (server returned **NO_SUCH_CLIENT** status code) - **Exception** - server returned one of the following status values: **BAD_OTP**, **BAD_SIGNATURE**, **MISSING_PARAMETER**, **OPERATION_NOT_ALLOWED**, **BACKEND_ERROR**, **NOT_ENOUGH_ANSWERS**, **REPLAYED_REQUEST** or no response was received from any of the servers in the specified time frame (default timeout = 10 seconds) [1]: http://www.yubico.com [2]: http://www.yubico.com/developers/intro/ [3]: http://www.yubico.com/develop/open-source-software/web-api-clients/server/ [4]: https://github.com/Yubico/yubikey-val/wiki/ValidationProtocolV20
yubico
/yubico-1.6.2.tar.gz/yubico-1.6.2/README.md
README.md
# YubiConvert YubiConvert - a Python module that can convert numeric words to their numerical form effortlessly. What's more, it supports both Western and Indian currency standards, making it the ultimate solution for all your numerical conversion needs. ## Installation To install the YubiConvert module, it is recommended to first ensure that you have updated the pip to the latest version. Then, you can use pip to install the module from the Python Package Index with the following command: ```python pip install yubiconvert ``` ## Usage Once the module is installed, you can import it into your Python code using the following line: ```python from yubiconvert import yubiconvert as w2n ``` Then you can use the **word_to_num** method to convert a number-word to numeric digits, as shown below. ```python print(w2n.word_to_num("twenty lakh three thousand nineteen Rupees")) 2003019 ``` ```python print(w2n.word_to_num('two point three')) 2.3 ``` ```python print(w2n.word_to_num('112')) 112 ``` ```python print(w2n.word_to_num('point one')) 0.1 ``` ```python print(w2n.word_to_num('one hundred thirty-five')) 135 ``` ```python print(w2n.word_to_num("there was a group of ten friends who went to the restaurant for a party, ordered thirty two dishes including ten drinks and bill came out as ten thousand five hundred and thirty paisa")) there was a group of 10 friends who went to the restaurant for a party, ordered 32 dishes including 10 drinks and bill came out as 10500.3 ``` ## Credits This repo is a forked of [w2n](https://github.com/akshaynagpal/w2n) library and the same has been used as a base to extend it further to support indian currency standards.
yubiconvert
/yubiconvert-1.0.4.tar.gz/yubiconvert-1.0.4/README.md
README.md
== python-yubihsm Python library and tests for the YubiHSM 2. This library is compatible with both Python 2 and 3. This library communicates with the YubiHSM 2 connector daemon, which must already be running. It can also communicate directly with the YubiHSM 2 via USB. === License .... Copyright 2018 Yubico AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. .... === Installation From PyPI: $ pip install yubihsm[http,usb] From a source .tar.gz: $ pip install yubihsm-<version>.tar.gz[http,usb] Omitting a tag from the brackets will install the library without support for that backend, and will avoid installing unneeded dependencies. === Quick reference commands: [source,python] ---- from yubihsm import YubiHsm from yubihsm.defs import CAPABILITY, ALGORITHM from yubihsm.objects import AsymmetricKey # Connect to the YubiHSM via the connector using the default password: hsm = YubiHsm.connect('http://localhost:12345') session = hsm.create_session_derived(1, 'password') # Generate a private key on the YubiHSM for creating signatures: key = AsymmetricKey.generate( # Generate a new key object in the YubiHSM. session, # Secure YubiHsm session to use. 0, # Object ID, 0 to get one assigned. 'My key', # Label for the object. 1, # Domain(s) for the object. CAPABILITY.SIGN_ECDSA, # Capabilities for the object. ALGORITHM.EC_P256 # Algorithm for the key. ) # pub_key is a cryptography.io ec.PublicKey, see https://cryptography.io pub_key = key.get_public_key() # Write the public key to a file: with open('public_key.pem', 'w') as f: f.write(pub_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo )) # Sign some data: signature = key.sign_ecdsa(b'Hello world!') # Create a signature. # Clean up session.close() hsm.close() ---- === Development For development of the library, we recommend using `pipenv`. To set up the dev environment, run this command in the root directory of the repository: $ pipenv install --dev ==== Running tests Running the tests require a YubiHSM2 to run against, with the default authentication key set. WARNING: The YubiHSM under test will be factory reset by the tests! $ pipenv run test You can specify a specific module or test to run by using the -s flag: $ pipenv run test -s test.device.test_ec By default the tests will connect to a yubihsm-connector running with the default settings on http://localhost:12345. To change this, use the `BACKEND` variable, eg: $ BACKEND="yhusb://" pipenv run python setup.py test Access to the device requires proper permissions, so either use sudo or setup a udev rule. ==== Generating HTML documentation To build the HTML documentation, run: $ pipenv run docs The resulting output will be in docs/_build/html/. ==== Source releases for distribution Build a source release: $ pipenv run python setup.py sdist The resulting .tar.gz will be created in `dist/`.
yubihsm
/yubihsm-2.1.3.tar.gz/yubihsm-2.1.3/README.adoc
README.adoc
== YubiKey Manager CLI image:https://github.com/Yubico/yubikey-manager/workflows/build/badge.svg["Build Status", link="https://github.com/Yubico/yubikey-manager/actions"] Python 3.7 (or later) library and command line tool for configuring a YubiKey. If you're looking for the graphical application, it's https://developers.yubico.com/yubikey-manager-qt/[here]. === Usage For more usage information and examples, see the https://docs.yubico.com/software/yubikey/tools/ykman/Using_the_ykman_CLI.html[YubiKey Manager CLI User Manual]. .... Usage: ykman [OPTIONS] COMMAND [ARGS]... Configure your YubiKey via the command line. Examples: List connected YubiKeys, only output serial number: $ ykman list --serials Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info Options: -d, --device SERIAL specify which YubiKey to interact with by serial number -r, --reader NAME specify a YubiKey by smart card reader name (can't be used with --device or list) -l, --log-level [ERROR|WARNING|INFO|DEBUG|TRAFFIC] enable logging at given verbosity level --log-file FILE write log to FILE instead of printing to stderr (requires --log-level) --diagnose show diagnostics information useful for troubleshooting -v, --version show version information about the app --full-help show --help output, including hidden commands -h, --help show this message and exit Commands: info show general information list list connected YubiKeys config enable or disable applications fido manage the FIDO applications oath manage the OATH application openpgp manage the OpenPGP application otp manage the YubiOTP application piv manage the PIV application .... The `--help` argument can also be used to get detailed information about specific subcommands: ykman oath --help === Versioning/Compatibility This project follows https://semver.org/[Semantic Versioning]. Any project depending on yubikey-manager should take care when specifying version ranges to not include any untested major version, as it is likely to have backwards incompatible changes. For example, you should NOT depend on ">=5", as it has no upper bound. Instead, depend on ">=5, <6", as any release before 6 will be compatible. Note that any private variables (names starting with '_') are not part of the public API, and may be changed between versions at any time. === Installation YubiKey Manager can be installed independently of platform by using pip (or equivalent): pip install --user yubikey-manager On Linux platforms you will need `pcscd` installed and running to be able to communicate with a YubiKey over the SmartCard interface. Additionally, you may need to set permissions for your user to access YubiKeys via the HID interfaces. More information available link:doc/Device_Permissions.adoc[here]. Some of the libraries used by yubikey-manager have C-extensions, and may require additional dependencies to build, such as http://www.swig.org/[swig] and potentially https://pcsclite.apdu.fr/[PCSC lite]. === Pre-build packages Pre-built packages specific to your platform may be available from Yubico or third parties. Please refer to your platforms native package manager for detailed instructions on how to install, if available. ==== Windows A Windows installer is available to download from the https://github.com/Yubico/yubikey-manager/releases/latest[Releases page]. ==== MacOS A MacOS installer is available to download from the https://github.com/Yubico/yubikey-manager/releases/latest[Releases page]. Additionally, packages are available from Homebrew and MacPorts. ===== Input Monitoring access on MacOS When running one of the `ykman otp` commands you may run into an error such as: `Failed to open device for communication: -536870174`. This indicates a problem with the permission to access the OTP (keyboard) USB interface. To access a YubiKey over this interface the application needs the `Input Monitoring` permission. If you are not automatically prompted to grant this permission, you may have to do so manually. Note that it is the _terminal_ you are using that needs the permission, not the ykman executable. To add your terminal application to the `Input Monitoring` permission list, go to `System Preferences -> Security & Privacy -> Privacy -> Input Monitoring` to resolve this. ==== Linux Packages are available for several Linux distributions by third party package maintainers. Yubico also provides packages for Ubuntu in the yubico/stable PPA: $ sudo apt-add-repository ppa:yubico/stable $ sudo apt update $ sudo apt install yubikey-manager ==== FreeBSD Althought not being officially supported on this platform, YubiKey Manager can be installed on FreeBSD. It's available via its ports tree or as pre-built package. Should you opt to install and use YubiKey Manager on this platform, please be aware that it's **NOT** maintained by Yubico. To install the binary package, use `pkg install pyXY-yubikey-manager`, with `pyXY` specifying the version of Python the package was built for, so in order to install YubiKey Manager for Python 3.8, use: # pkg install py38-yubikey-manager For more information about how to install packages or ports on FreeBSD, please refer to its official documentation: https://docs.freebsd.org/en/books/handbook/ports[FreeBSD Handbook]. In order to use `ykman otp` commands, you need to make sure the _uhid(4)_ driver attaches to the USB device: # usbconfig ugenX.Y add_quirk UQ_KBD_IGNORE # usbconfig ugenX.Y reset The correct device to operate on _(ugenX.Y)_ can be determined using `usbconfig list`. When using FreeBSD 13 or higher, you can switch to the more modern _hidraw(4)_ driver. This allows YubiKey Manager to access OTP HID in a non-exclusive way, so that the key will still function as a USB keyboard: # sysrc kld_list+="hidraw hkbd" # cat >>/boot/loader.conf<<EOF hw.usb.usbhid.enable="1" hw.usb.quirk.0="0x1050 0x0010 0 0xffff UQ_KBD_IGNORE" # YKS_OTP hw.usb.quirk.1="0x1050 0x0110 0 0xffff UQ_KBD_IGNORE" # NEO_OTP hw.usb.quirk.2="0x1050 0x0111 0 0xffff UQ_KBD_IGNORE" # NEO_OTP_CCID hw.usb.quirk.3="0x1050 0x0114 0 0xffff UQ_KBD_IGNORE" # NEO_OTP_FIDO hw.usb.quirk.4="0x1050 0x0116 0 0xffff UQ_KBD_IGNORE" # NEO_OTP_FIDO_CCID hw.usb.quirk.5="0x1050 0x0401 0 0xffff UQ_KBD_IGNORE" # YK4_OTP hw.usb.quirk.6="0x1050 0x0403 0 0xffff UQ_KBD_IGNORE" # YK4_OTP_FIDO hw.usb.quirk.7="0x1050 0x0405 0 0xffff UQ_KBD_IGNORE" # YK4_OTP_CCID hw.usb.quirk.8="0x1050 0x0407 0 0xffff UQ_KBD_IGNORE" # YK4_OTP_FIDO_CCID hw.usb.quirk.9="0x1050 0x0410 0 0xffff UQ_KBD_IGNORE" # YKP_OTP_FIDO EOF # reboot ==== From source (for development) To install from source, see the link:doc/Development.adoc[development] instructions. === Shell completion Experimental shell completion for the command line tool is available, provided by the underlying CLI library (`click`) but it is not enabled by default. To enable it, run this command once (for Bash): $ source <(_YKMAN_COMPLETE=bash_source ykman | sudo tee /etc/bash_completion.d/ykman) More information on shell completion (including instructions for zch) is available here: https://click.palletsprojects.com/en/8.0.x/shell-completion
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/README.adoc
README.adoc
from .core import ( int2bytes, bytes2int, require_version, Version, Tlv, BadResponseError, ) from .core.smartcard import AID, SmartCardConnection, SmartCardProtocol from urllib.parse import unquote, urlparse, parse_qs from functools import total_ordering from enum import IntEnum, unique from dataclasses import dataclass from base64 import b64encode, b32decode from time import time from typing import Optional, List, Mapping import hmac import hashlib import struct import os import re import logging logger = logging.getLogger(__name__) # TLV tags for credential data TAG_NAME = 0x71 TAG_NAME_LIST = 0x72 TAG_KEY = 0x73 TAG_CHALLENGE = 0x74 TAG_RESPONSE = 0x75 TAG_TRUNCATED = 0x76 TAG_HOTP = 0x77 TAG_PROPERTY = 0x78 TAG_VERSION = 0x79 TAG_IMF = 0x7A TAG_TOUCH = 0x7C # Instruction bytes for commands INS_LIST = 0xA1 INS_PUT = 0x01 INS_DELETE = 0x02 INS_SET_CODE = 0x03 INS_RESET = 0x04 INS_RENAME = 0x05 INS_CALCULATE = 0xA2 INS_VALIDATE = 0xA3 INS_CALCULATE_ALL = 0xA4 INS_SEND_REMAINING = 0xA5 TOTP_ID_PATTERN = re.compile(r"^((\d+)/)?(([^:]+):)?(.+)$") MASK_ALGO = 0x0F MASK_TYPE = 0xF0 DEFAULT_PERIOD = 30 DEFAULT_DIGITS = 6 DEFAULT_IMF = 0 CHALLENGE_LEN = 8 HMAC_MINIMUM_KEY_SIZE = 14 @unique class HASH_ALGORITHM(IntEnum): SHA1 = 0x01 SHA256 = 0x02 SHA512 = 0x03 @unique class OATH_TYPE(IntEnum): HOTP = 0x10 TOTP = 0x20 PROP_REQUIRE_TOUCH = 0x02 def parse_b32_key(key: str): """Parse Base32 encoded key. :param key: The Base32 encoded key. """ key = key.upper().replace(" ", "") key += "=" * (-len(key) % 8) # Support unpadded return b32decode(key) def _parse_select(response): data = Tlv.parse_dict(response) return ( Version.from_bytes(data[TAG_VERSION]), data.get(TAG_NAME), data.get(TAG_CHALLENGE), ) @dataclass class CredentialData: """An object holding OATH credential data.""" name: str oath_type: OATH_TYPE hash_algorithm: HASH_ALGORITHM secret: bytes digits: int = DEFAULT_DIGITS period: int = DEFAULT_PERIOD counter: int = DEFAULT_IMF issuer: Optional[str] = None @classmethod def parse_uri(cls, uri: str) -> "CredentialData": """Parse OATH credential data from URI. :param uri: The URI to parse from. """ parsed = urlparse(uri.strip()) if parsed.scheme != "otpauth": raise ValueError("Invalid URI scheme") if parsed.hostname is None: raise ValueError("Missing OATH type") oath_type = OATH_TYPE[parsed.hostname.upper()] params = dict((k, v[0]) for k, v in parse_qs(parsed.query).items()) issuer = None name = unquote(parsed.path)[1:] # Unquote and strip leading / if ":" in name: issuer, name = name.split(":", 1) return cls( name=name, oath_type=oath_type, hash_algorithm=HASH_ALGORITHM[params.get("algorithm", "SHA1").upper()], secret=parse_b32_key(params["secret"]), digits=int(params.get("digits", DEFAULT_DIGITS)), period=int(params.get("period", DEFAULT_PERIOD)), counter=int(params.get("counter", DEFAULT_IMF)), issuer=params.get("issuer", issuer), ) def get_id(self) -> bytes: return _format_cred_id(self.issuer, self.name, self.oath_type, self.period) @dataclass class Code: """An OATH code object.""" value: str valid_from: int valid_to: int @total_ordering @dataclass(order=False, frozen=True) class Credential: """An OATH credential object.""" device_id: str id: bytes issuer: Optional[str] name: str oath_type: OATH_TYPE period: int touch_required: Optional[bool] def __lt__(self, other): a = ((self.issuer or self.name).lower(), self.name.lower()) b = ((other.issuer or other.name).lower(), other.name.lower()) return a < b def __eq__(self, other): return ( isinstance(other, type(self)) and self.device_id == other.device_id and self.id == other.id ) def __hash__(self): return hash((self.device_id, self.id)) def _format_cred_id(issuer, name, oath_type, period=DEFAULT_PERIOD): cred_id = "" if oath_type == OATH_TYPE.TOTP and period != DEFAULT_PERIOD: cred_id += "%d/" % period if issuer: cred_id += issuer + ":" cred_id += name return cred_id.encode() def _parse_cred_id(cred_id, oath_type): data = cred_id.decode() if oath_type == OATH_TYPE.TOTP: match = TOTP_ID_PATTERN.match(data) if match: period_str = match.group(2) return ( match.group(4), match.group(5), int(period_str) if period_str else DEFAULT_PERIOD, ) else: return None, data, DEFAULT_PERIOD else: if ":" in data: issuer, data = data.split(":", 1) else: issuer = None return issuer, data, 0 def _get_device_id(salt): d = hashlib.sha256(salt).digest()[:16] return b64encode(d).replace(b"=", b"").decode() def _hmac_sha1(key, message): return hmac.new(key, message, "sha1").digest() def _derive_key(salt, passphrase): return hashlib.pbkdf2_hmac("sha1", passphrase.encode(), salt, 1000, 16) def _hmac_shorten_key(key, algo): h = hashlib.new(algo.name) if len(key) > h.block_size: h.update(key) key = h.digest() return key def _get_challenge(timestamp, period): time_step = timestamp // period return struct.pack(">q", time_step) def _format_code(credential, timestamp, truncated): if credential.oath_type == OATH_TYPE.TOTP: time_step = timestamp // credential.period valid_from = time_step * credential.period valid_to = (time_step + 1) * credential.period else: # HOTP valid_from = timestamp valid_to = 0x7FFFFFFFFFFFFFFF digits = truncated[0] return Code( str((bytes2int(truncated[1:]) & 0x7FFFFFFF) % 10**digits).rjust(digits, "0"), valid_from, valid_to, ) class OathSession: """A session with the OATH application.""" def __init__(self, connection: SmartCardConnection): self.protocol = SmartCardProtocol(connection, INS_SEND_REMAINING) self._version, self._salt, self._challenge = _parse_select( self.protocol.select(AID.OATH) ) self._has_key = self._challenge is not None self._device_id = _get_device_id(self._salt) self.protocol.enable_touch_workaround(self._version) self._neo_unlock_workaround = self.version < (3, 0, 0) logger.debug( f"OATH session initialized (version={self.version}, " f"has_key={self._has_key})" ) @property def version(self) -> Version: """The OATH application version.""" return self._version @property def device_id(self) -> str: """The device ID.""" return self._device_id @property def has_key(self) -> bool: """If True, the YubiKey has an access key.""" return self._has_key @property def locked(self) -> bool: """If True, the OATH application is password protected.""" return self._challenge is not None def reset(self) -> None: """Perform a factory reset on the OATH application.""" self.protocol.send_apdu(0, INS_RESET, 0xDE, 0xAD) _, self._salt, self._challenge = _parse_select(self.protocol.select(AID.OATH)) logger.info("OATH application data reset performed") self._has_key = False self._device_id = _get_device_id(self._salt) def derive_key(self, password: str) -> bytes: """Derive a key from password. :param password: The derivation password. """ return _derive_key(self._salt, password) def validate(self, key: bytes) -> None: """Validate authentication with access key. :param key: The access key. """ logger.debug("Unlocking session") response = _hmac_sha1(key, self._challenge) challenge = os.urandom(8) data = Tlv(TAG_RESPONSE, response) + Tlv(TAG_CHALLENGE, challenge) resp = self.protocol.send_apdu(0, INS_VALIDATE, 0, 0, data) verification = _hmac_sha1(key, challenge) if not hmac.compare_digest(Tlv.unpack(TAG_RESPONSE, resp), verification): raise BadResponseError( "Response from validation does not match verification!" ) self._challenge = None self._neo_unlock_workaround = False def set_key(self, key: bytes) -> None: """Set access key for authentication. :param key: The access key. """ challenge = os.urandom(8) response = _hmac_sha1(key, challenge) self.protocol.send_apdu( 0, INS_SET_CODE, 0, 0, ( Tlv(TAG_KEY, int2bytes(OATH_TYPE.TOTP | HASH_ALGORITHM.SHA1) + key) + Tlv(TAG_CHALLENGE, challenge) + Tlv(TAG_RESPONSE, response) ), ) logger.info("New access code set") self._has_key = True if self._neo_unlock_workaround: logger.debug("Performing NEO workaround, re-select and unlock") self._challenge = _parse_select(self.protocol.select(AID.OATH))[2] self.validate(key) def unset_key(self) -> None: """Remove access code. WARNING: This removes authentication. """ self.protocol.send_apdu(0, INS_SET_CODE, 0, 0, Tlv(TAG_KEY)) logger.info("Access code removed") self._has_key = False def put_credential( self, credential_data: CredentialData, touch_required: bool = False ) -> Credential: """Add a OATH credential. :param credential_data: The credential data. :param touch_required: The touch policy. """ d = credential_data cred_id = d.get_id() secret = _hmac_shorten_key(d.secret, d.hash_algorithm) secret = secret.ljust(HMAC_MINIMUM_KEY_SIZE, b"\0") data = Tlv(TAG_NAME, cred_id) + Tlv( TAG_KEY, struct.pack(">BB", d.oath_type | d.hash_algorithm, d.digits) + secret, ) if touch_required: data += struct.pack(">BB", TAG_PROPERTY, PROP_REQUIRE_TOUCH) if d.counter > 0: data += Tlv(TAG_IMF, struct.pack(">I", d.counter)) logger.debug( f"Importing credential (type={d.oath_type!r}, hash={d.hash_algorithm!r}, " f"digits={d.digits}, period={d.period}, imf={d.counter}, " f"touch_required={touch_required})" ) self.protocol.send_apdu(0, INS_PUT, 0, 0, data) logger.info("Credential imported") return Credential( self.device_id, cred_id, d.issuer, d.name, d.oath_type, d.period, touch_required, ) def rename_credential( self, credential_id: bytes, name: str, issuer: Optional[str] = None ) -> bytes: """Rename a OATH credential. :param credential_id: The id of the credential. :param name: The new name of the credential. :param issuer: The credential issuer. """ require_version(self.version, (5, 3, 1)) _, _, period = _parse_cred_id(credential_id, OATH_TYPE.TOTP) new_id = _format_cred_id(issuer, name, OATH_TYPE.TOTP, period) self.protocol.send_apdu( 0, INS_RENAME, 0, 0, Tlv(TAG_NAME, credential_id) + Tlv(TAG_NAME, new_id) ) logger.info("Credential renamed") return new_id def list_credentials(self) -> List[Credential]: """List OATH credentials.""" creds = [] for tlv in Tlv.parse_list(self.protocol.send_apdu(0, INS_LIST, 0, 0)): data = Tlv.unpack(TAG_NAME_LIST, tlv) oath_type = OATH_TYPE(MASK_TYPE & data[0]) cred_id = data[1:] issuer, name, period = _parse_cred_id(cred_id, oath_type) creds.append( Credential( self.device_id, cred_id, issuer, name, oath_type, period, None ) ) return creds def calculate(self, credential_id: bytes, challenge: bytes) -> bytes: """Perform a calculate for an OATH credential. :param credential_id: The id of the credential. :param challenge: The challenge. """ resp = Tlv.unpack( TAG_RESPONSE, self.protocol.send_apdu( 0, INS_CALCULATE, 0, 0, Tlv(TAG_NAME, credential_id) + Tlv(TAG_CHALLENGE, challenge), ), ) return resp[1:] def delete_credential(self, credential_id: bytes) -> None: """Delete an OATH credential. :param credential_id: The id of the credential. """ self.protocol.send_apdu(0, INS_DELETE, 0, 0, Tlv(TAG_NAME, credential_id)) logger.info("Credential deleted") def calculate_all( self, timestamp: Optional[int] = None ) -> Mapping[Credential, Optional[Code]]: """Calculate codes for all OATH credentials on the YubiKey. :param timestamp: A timestamp. """ timestamp = int(timestamp or time()) challenge = _get_challenge(timestamp, DEFAULT_PERIOD) logger.debug(f"Calculating all codes for time={timestamp}") entries = {} data = Tlv.parse_list( self.protocol.send_apdu( 0, INS_CALCULATE_ALL, 0, 1, Tlv(TAG_CHALLENGE, challenge) ) ) while data: cred_id = Tlv.unpack(TAG_NAME, data.pop(0)) tlv = data.pop(0) resp_tag = tlv.tag oath_type = OATH_TYPE.HOTP if resp_tag == TAG_HOTP else OATH_TYPE.TOTP touch = resp_tag == TAG_TOUCH issuer, name, period = _parse_cred_id(cred_id, oath_type) credential = Credential( self.device_id, cred_id, issuer, name, oath_type, period, touch ) code = None # Will be None for HOTP and touch if resp_tag == TAG_TRUNCATED: # Only TOTP, no-touch here if period == DEFAULT_PERIOD: code = _format_code(credential, timestamp, tlv.value) else: # Non-standard period, recalculate logger.debug(f"Recalculating code for period={period}") code = self.calculate_code(credential, timestamp) entries[credential] = code return entries def calculate_code( self, credential: Credential, timestamp: Optional[int] = None ) -> Code: """Calculate code for an OATH credential. :param credential: The credential object. :param timestamp: The timestamp. """ if credential.device_id != self.device_id: raise ValueError("Credential does not belong to this YubiKey") timestamp = int(timestamp or time()) if credential.oath_type == OATH_TYPE.TOTP: logger.debug( f"Calculating TOTP code for time={timestamp}, " f"period={credential.period}" ) challenge = _get_challenge(timestamp, credential.period) else: # HOTP logger.debug("Calculating HOTP code") challenge = b"" response = Tlv.unpack( TAG_TRUNCATED, self.protocol.send_apdu( 0, INS_CALCULATE, 0, 0x01, # Truncate Tlv(TAG_NAME, credential.id) + Tlv(TAG_CHALLENGE, challenge), ), ) return _format_code(credential, timestamp, response)
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/oath.py
oath.py
from .core import ( int2bytes, bytes2int, require_version, Version, Tlv, InvalidPinError, ) from .core.smartcard import AID, SmartCardConnection, SmartCardProtocol, ApduError, SW from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives.asymmetric import ec from functools import total_ordering from enum import IntEnum, unique from dataclasses import dataclass from typing import Optional, List, Union, Tuple, NamedTuple import struct import logging logger = logging.getLogger(__name__) # TLV tags for credential data TAG_LABEL = 0x71 TAG_LABEL_LIST = 0x72 TAG_CREDENTIAL_PASSWORD = 0x73 TAG_ALGORITHM = 0x74 TAG_KEY_ENC = 0x75 TAG_KEY_MAC = 0x76 TAG_CONTEXT = 0x77 TAG_RESPONSE = 0x78 TAG_VERSION = 0x79 TAG_TOUCH = 0x7A TAG_MANAGEMENT_KEY = 0x7B TAG_PUBLIC_KEY = 0x7C TAG_PRIVATE_KEY = 0x7D # Instruction bytes for commands INS_PUT = 0x01 INS_DELETE = 0x02 INS_CALCULATE = 0x03 INS_GET_CHALLENGE = 0x04 INS_LIST = 0x05 INS_RESET = 0x06 INS_GET_VERSION = 0x07 INS_PUT_MANAGEMENT_KEY = 0x08 INS_GET_MANAGEMENT_KEY_RETRIES = 0x09 INS_GET_PUBLIC_KEY = 0x0A # Lengths for paramters MANAGEMENT_KEY_LEN = 16 CREDENTIAL_PASSWORD_LEN = 16 MIN_LABEL_LEN = 1 MAX_LABEL_LEN = 64 DEFAULT_MANAGEMENT_KEY = ( b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" ) INITIAL_RETRY_COUNTER = 8 @unique class ALGORITHM(IntEnum): """Algorithms for YubiHSM Auth credentials.""" AES128_YUBICO_AUTHENTICATION = 38 EC_P256_YUBICO_AUTHENTICATION = 39 @property def key_len(self): if self.name.startswith("AES128"): return 16 elif self.name.startswith("EC_P256"): return 32 @property def pubkey_len(self): if self.name.startswith("EC_P256"): return 64 def _parse_credential_password(credential_password: Union[bytes, str]) -> bytes: if isinstance(credential_password, str): pw = credential_password.encode().ljust(CREDENTIAL_PASSWORD_LEN, b"\0") else: pw = bytes(credential_password) if len(pw) != CREDENTIAL_PASSWORD_LEN: raise ValueError( "Credential password must be %d bytes long" % CREDENTIAL_PASSWORD_LEN ) return pw def _parse_label(label: str) -> bytes: try: parsed_label = label.encode() except Exception: raise ValueError(label) if len(parsed_label) < MIN_LABEL_LEN or len(parsed_label) > MAX_LABEL_LEN: raise ValueError( "Label must be between %d and %d bytes long" % (MIN_LABEL_LEN, MAX_LABEL_LEN) ) return parsed_label def _parse_select(response): data = Tlv.unpack(TAG_VERSION, response) return Version.from_bytes(data) def _password_to_key(password: str) -> Tuple[bytes, bytes]: """Derive encryption and MAC key from a password. :return: A tuple containing the encryption key, and MAC key. """ pw_bytes = password.encode() key = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=b"Yubico", iterations=10000, backend=default_backend(), ).derive(pw_bytes) key_enc, key_mac = key[:16], key[16:] return key_enc, key_mac def _retries_from_sw(sw): if sw & 0xFFF0 == SW.VERIFY_FAIL_NO_RETRY: return sw & ~0xFFF0 return None @total_ordering @dataclass(order=False, frozen=True) class Credential: """A YubiHSM Auth credential object.""" label: str algorithm: ALGORITHM counter: int touch_required: Optional[bool] def __lt__(self, other): a = self.label.lower() b = other.label.lower() return a < b def __eq__(self, other): return self.label == other.label def __hash__(self) -> int: return hash(self.label) class SessionKeys(NamedTuple): """YubiHSM Session Keys.""" key_senc: bytes key_smac: bytes key_srmac: bytes @classmethod def parse(cls, response: bytes) -> "SessionKeys": key_senc = response[:16] key_smac = response[16:32] key_srmac = response[32:48] return cls( key_senc=key_senc, key_smac=key_smac, key_srmac=key_srmac, ) class HsmAuthSession: """A session with the YubiHSM Auth application.""" def __init__(self, connection: SmartCardConnection) -> None: self.protocol = SmartCardProtocol(connection) self._version = _parse_select(self.protocol.select(AID.HSMAUTH)) @property def version(self) -> Version: """The YubiHSM Auth application version.""" return self._version def reset(self) -> None: """Perform a factory reset on the YubiHSM Auth application.""" self.protocol.send_apdu(0, INS_RESET, 0xDE, 0xAD) logger.info("YubiHSM Auth application data reset performed") def list_credentials(self) -> List[Credential]: """List YubiHSM Auth credentials on YubiKey""" creds = [] for tlv in Tlv.parse_list(self.protocol.send_apdu(0, INS_LIST, 0, 0)): data = Tlv.unpack(TAG_LABEL_LIST, tlv) algorithm = ALGORITHM(data[0]) touch_required = bool(data[1]) label_length = tlv.length - 3 label = data[2 : 2 + label_length].decode() counter = data[-1] creds.append(Credential(label, algorithm, counter, touch_required)) return creds def _put_credential( self, management_key: bytes, label: str, key: bytes, algorithm: ALGORITHM, credential_password: Union[bytes, str], touch_required: bool = False, ) -> Credential: if len(management_key) != MANAGEMENT_KEY_LEN: raise ValueError( "Management key must be %d bytes long" % MANAGEMENT_KEY_LEN ) data = ( Tlv(TAG_MANAGEMENT_KEY, management_key) + Tlv(TAG_LABEL, _parse_label(label)) + Tlv(TAG_ALGORITHM, int2bytes(algorithm)) ) if algorithm == ALGORITHM.AES128_YUBICO_AUTHENTICATION: data += Tlv(TAG_KEY_ENC, key[:16]) + Tlv(TAG_KEY_MAC, key[16:]) elif algorithm == ALGORITHM.EC_P256_YUBICO_AUTHENTICATION: data += Tlv(TAG_PRIVATE_KEY, key) data += Tlv( TAG_CREDENTIAL_PASSWORD, _parse_credential_password(credential_password) ) if touch_required: data += Tlv(TAG_TOUCH, int2bytes(1)) else: data += Tlv(TAG_TOUCH, int2bytes(0)) logger.debug( f"Importing YubiHSM Auth credential (label={label}, algo={algorithm}, " f"touch_required={touch_required})" ) try: self.protocol.send_apdu(0, INS_PUT, 0, 0, data) logger.info("Credential imported") except ApduError as e: retries = _retries_from_sw(e.sw) if retries is None: raise raise InvalidPinError( attempts_remaining=retries, message=f"Invalid management key, {retries} attempts remaining", ) return Credential(label, algorithm, INITIAL_RETRY_COUNTER, touch_required) def put_credential_symmetric( self, management_key: bytes, label: str, key_enc: bytes, key_mac: bytes, credential_password: Union[bytes, str], touch_required: bool = False, ) -> Credential: """Import a symmetric YubiHSM Auth credential. :param management_key: The management key. :param label: The label of the credential. :param key_enc: The static K-ENC. :param key_mac: The static K-MAC. :param credential_password: The password used to protect access to the credential. :param touch_required: The touch requirement policy. """ aes128_key_len = ALGORITHM.AES128_YUBICO_AUTHENTICATION.key_len if len(key_enc) != aes128_key_len or len(key_mac) != aes128_key_len: raise ValueError( "Encryption and MAC key must be %d bytes long", aes128_key_len ) return self._put_credential( management_key, label, key_enc + key_mac, ALGORITHM.AES128_YUBICO_AUTHENTICATION, credential_password, touch_required, ) def put_credential_derived( self, management_key: bytes, label: str, derivation_password: str, credential_password: Union[bytes, str], touch_required: bool = False, ) -> Credential: """Import a symmetric YubiHSM Auth credential derived from password. :param management_key: The management key. :param label: The label of the credential. :param derivation_password: The password used to derive the keys from. :param credential_password: The password used to protect access to the credential. :param touch_required: The touch requirement policy. """ key_enc, key_mac = _password_to_key(derivation_password) return self.put_credential_symmetric( management_key, label, key_enc, key_mac, credential_password, touch_required ) def put_credential_asymmetric( self, management_key: bytes, label: str, private_key: ec.EllipticCurvePrivateKeyWithSerialization, credential_password: Union[bytes, str], touch_required: bool = False, ) -> Credential: """Import an asymmetric YubiHSM Auth credential. :param management_key: The management key. :param label: The label of the credential. :param private_key: Private key corresponding to the public authentication key object on the YubiHSM. :param credential_password: The password used to protect access to the credential. :param touch_required: The touch requirement policy. """ require_version(self.version, (5, 6, 0)) if not isinstance(private_key.curve, ec.SECP256R1): raise ValueError("Unsupported curve") ln = ALGORITHM.EC_P256_YUBICO_AUTHENTICATION.key_len numbers = private_key.private_numbers() return self._put_credential( management_key, label, int2bytes(numbers.private_value, ln), ALGORITHM.EC_P256_YUBICO_AUTHENTICATION, credential_password, touch_required, ) def generate_credential_asymmetric( self, management_key: bytes, label: str, credential_password: Union[bytes, str], touch_required: bool = False, ) -> Credential: """Generate an asymmetric YubiHSM Auth credential. Generates a private key on the YubiKey, whose corresponding public key can be retrieved using `get_public_key`. :param management_key: The management key. :param label: The label of the credential. :param credential_password: The password used to protect access to the credential. :param touch_required: The touch requirement policy. """ require_version(self.version, (5, 6, 0)) return self._put_credential( management_key, label, b"", # Emtpy byte will generate key ALGORITHM.EC_P256_YUBICO_AUTHENTICATION, credential_password, touch_required, ) def get_public_key(self, label: str) -> ec.EllipticCurvePublicKey: """Get the public key for an asymmetric credential. This will return the long-term public key "PK-OCE" for an asymmetric credential. :param label: The label of the credential. """ require_version(self.version, (5, 6, 0)) data = Tlv(TAG_LABEL, _parse_label(label)) res = self.protocol.send_apdu(0, INS_GET_PUBLIC_KEY, 0, 0, data) return ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), res) def delete_credential(self, management_key: bytes, label: str) -> None: """Delete a YubiHSM Auth credential. :param management_key: The management key. :param label: The label of the credential. """ if len(management_key) != MANAGEMENT_KEY_LEN: raise ValueError( "Management key must be %d bytes long" % MANAGEMENT_KEY_LEN ) data = Tlv(TAG_MANAGEMENT_KEY, management_key) + Tlv( TAG_LABEL, _parse_label(label) ) try: self.protocol.send_apdu(0, INS_DELETE, 0, 0, data) logger.info("Credential deleted") except ApduError as e: retries = _retries_from_sw(e.sw) if retries is None: raise raise InvalidPinError( attempts_remaining=retries, message=f"Invalid management key, {retries} attempts remaining", ) def put_management_key( self, management_key: bytes, new_management_key: bytes, ) -> None: """Change YubiHSM Auth management key :param management_key: The current management key. :param new_management_key: The new management key. """ if ( len(management_key) != MANAGEMENT_KEY_LEN or len(new_management_key) != MANAGEMENT_KEY_LEN ): raise ValueError( "Management key must be %d bytes long" % MANAGEMENT_KEY_LEN ) data = Tlv(TAG_MANAGEMENT_KEY, management_key) + Tlv( TAG_MANAGEMENT_KEY, new_management_key ) try: self.protocol.send_apdu(0, INS_PUT_MANAGEMENT_KEY, 0, 0, data) logger.info("New management key set") except ApduError as e: retries = _retries_from_sw(e.sw) if retries is None: raise raise InvalidPinError( attempts_remaining=retries, message=f"Invalid management key, {retries} attempts remaining", ) def get_management_key_retries(self) -> int: """Get retries remaining for Management key""" res = self.protocol.send_apdu(0, INS_GET_MANAGEMENT_KEY_RETRIES, 0, 0) return bytes2int(res) def _calculate_session_keys( self, label: str, context: bytes, credential_password: Union[bytes, str], card_crypto: Optional[bytes] = None, public_key: Optional[bytes] = None, ) -> bytes: data = Tlv(TAG_LABEL, _parse_label(label)) + Tlv(TAG_CONTEXT, context) if public_key: data += Tlv(TAG_PUBLIC_KEY, public_key) if card_crypto: data += Tlv(TAG_RESPONSE, card_crypto) data += Tlv( TAG_CREDENTIAL_PASSWORD, _parse_credential_password(credential_password) ) try: res = self.protocol.send_apdu(0, INS_CALCULATE, 0, 0, data) logger.info("Session keys calculated") except ApduError as e: retries = _retries_from_sw(e.sw) if retries is None: raise raise InvalidPinError( attempts_remaining=retries, message=f"Invalid credential password, {retries} attempts remaining", ) return res def calculate_session_keys_symmetric( self, label: str, context: bytes, credential_password: Union[bytes, str], card_crypto: Optional[bytes] = None, ) -> SessionKeys: """Calculate session keys from a symmetric YubiHSM Auth credential. :param label: The label of the credential. :param context: The context (host challenge + hsm challenge). :param credential_password: The password used to protect access to the credential. :param card_crypto: The card cryptogram. """ return SessionKeys.parse( self._calculate_session_keys( label=label, context=context, credential_password=credential_password, card_crypto=card_crypto, ) ) def calculate_session_keys_asymmetric( self, label: str, context: bytes, public_key: ec.EllipticCurvePublicKey, credential_password: Union[bytes, str], card_crypto: bytes, ) -> SessionKeys: """Calculate session keys from an asymmetric YubiHSM Auth credential. :param label: The label of the credential. :param context: The context (EPK.OCE + EPK.SD). :param public_key: The YubiHSM device's public key. :param credential_password: The password used to protect access to the credential. :param card_crypto: The card cryptogram. """ require_version(self.version, (5, 6, 0)) if not isinstance(public_key.curve, ec.SECP256R1): raise ValueError("Unsupported curve") numbers = public_key.public_numbers() public_key_data = ( struct.pack("!B", 4) + int.to_bytes(numbers.x, public_key.key_size // 8, "big") + int.to_bytes(numbers.y, public_key.key_size // 8, "big") ) return SessionKeys.parse( self._calculate_session_keys( label=label, context=context, credential_password=credential_password, card_crypto=card_crypto, public_key=public_key_data, ) ) def get_challenge(self, label: str) -> bytes: """Get the Host Challenge. For symmetric credentials this is Host Challenge, a random 8 byte value. For asymmetric credentials this is EPK-OCE. :param label: The label of the credential. """ require_version(self.version, (5, 6, 0)) data = Tlv(TAG_LABEL, _parse_label(label)) return self.protocol.send_apdu(0, INS_GET_CHALLENGE, 0, 0, data)
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/hsmauth.py
hsmauth.py
from .core import ( TRANSPORT, Version, bytes2int, require_version, NotSupportedError, BadResponseError, ) from .core import ApplicationNotAvailableError from .core.otp import ( check_crc, calculate_crc, OtpConnection, OtpProtocol, CommandRejectedError, ) from .core.smartcard import AID, SmartCardConnection, SmartCardProtocol import abc import struct from hashlib import sha1 from threading import Event from enum import unique, IntEnum, IntFlag from typing import TypeVar, Optional, Union, Callable import logging logger = logging.getLogger(__name__) T = TypeVar("T") @unique class SLOT(IntEnum): ONE = 1 TWO = 2 @staticmethod def map(slot: "SLOT", one: T, two: T) -> T: if slot == 1: return one elif slot == 2: return two raise ValueError("Invalid slot (must be 1 or 2)") @unique class CONFIG_SLOT(IntEnum): CONFIG_1 = 1 # First (default / V1) configuration NAV = 2 # V1 only CONFIG_2 = 3 # Second (V2) configuration UPDATE_1 = 4 # Update slot 1 UPDATE_2 = 5 # Update slot 2 SWAP = 6 # Swap slot 1 and 2 NDEF_1 = 8 # Write NDEF record NDEF_2 = 9 # Write NDEF record for slot 2 DEVICE_SERIAL = 0x10 # Device serial number DEVICE_CONFIG = 0x11 # Write device configuration record SCAN_MAP = 0x12 # Write scancode map YK4_CAPABILITIES = 0x13 # Read YK4 capabilities (device info) list YK4_SET_DEVICE_INFO = 0x15 # Write device info CHAL_OTP_1 = 0x20 # Write 6 byte challenge to slot 1, get Yubico OTP response CHAL_OTP_2 = 0x28 # Write 6 byte challenge to slot 2, get Yubico OTP response CHAL_HMAC_1 = 0x30 # Write 64 byte challenge to slot 1, get HMAC-SHA1 response CHAL_HMAC_2 = 0x38 # Write 64 byte challenge to slot 2, get HMAC-SHA1 response class TKTFLAG(IntFlag): # Yubikey 1 and above TAB_FIRST = 0x01 # Send TAB before first part APPEND_TAB1 = 0x02 # Send TAB after first part APPEND_TAB2 = 0x04 # Send TAB after second part APPEND_DELAY1 = 0x08 # Add 0.5s delay after first part APPEND_DELAY2 = 0x10 # Add 0.5s delay after second part APPEND_CR = 0x20 # Append CR as final character # Yubikey 2 and above PROTECT_CFG2 = 0x80 # Block update of config 2 unless config 2 is configured and has this bit set # Yubikey 2.1 and above OATH_HOTP = 0x40 # OATH HOTP mode # Yubikey 2.2 and above CHAL_RESP = 0x40 # Challenge-response enabled (both must be set) class CFGFLAG(IntFlag): # Yubikey 1 and above SEND_REF = 0x01 # Send reference string (0..F) before data PACING_10MS = 0x04 # Add 10ms intra-key pacing PACING_20MS = 0x08 # Add 20ms intra-key pacing STATIC_TICKET = 0x20 # Static ticket generation # Yubikey 1 only TICKET_FIRST = 0x02 # Send ticket first (default is fixed part) ALLOW_HIDTRIG = 0x10 # Allow trigger through HID/keyboard # Yubikey 2 and above SHORT_TICKET = 0x02 # Send truncated ticket (half length) STRONG_PW1 = 0x10 # Strong password policy flag #1 (mixed case) STRONG_PW2 = 0x40 # Strong password policy flag #2 (subtitute 0..7 to digits) MAN_UPDATE = 0x80 # Allow manual (local) update of static OTP # Yubikey 2.1 and above OATH_HOTP8 = 0x02 # Generate 8 digits HOTP rather than 6 digits OATH_FIXED_MODHEX1 = 0x10 # First byte in fixed part sent as modhex OATH_FIXED_MODHEX2 = 0x40 # First two bytes in fixed part sent as modhex OATH_FIXED_MODHEX = 0x50 # Fixed part sent as modhex OATH_FIXED_MASK = 0x50 # Mask to get out fixed flags # Yubikey 2.2 and above CHAL_YUBICO = 0x20 # Challenge-response enabled - Yubico OTP mode CHAL_HMAC = 0x22 # Challenge-response enabled - HMAC-SHA1 HMAC_LT64 = 0x04 # Set when HMAC message is less than 64 bytes CHAL_BTN_TRIG = 0x08 # Challenge-response operation requires button press class EXTFLAG(IntFlag): SERIAL_BTN_VISIBLE = 0x01 # Serial number visible at startup (button press) SERIAL_USB_VISIBLE = 0x02 # Serial number visible in USB iSerial field SERIAL_API_VISIBLE = 0x04 # Serial number visible via API call # V2.3 flags only USE_NUMERIC_KEYPAD = 0x08 # Use numeric keypad for digits FAST_TRIG = 0x10 # Use fast trig if only cfg1 set ALLOW_UPDATE = 0x20 # Allow update of existing configuration (selected flags + access code) DORMANT = 0x40 # Dormant config (woken up, flag removed, requires update flag) # V2.4/3.1 flags only LED_INV = 0x80 # LED idle state is off rather than on # Flags valid for update TKTFLAG_UPDATE_MASK = ( TKTFLAG.TAB_FIRST | TKTFLAG.APPEND_TAB1 | TKTFLAG.APPEND_TAB2 | TKTFLAG.APPEND_DELAY1 | TKTFLAG.APPEND_DELAY2 | TKTFLAG.APPEND_CR ) CFGFLAG_UPDATE_MASK = CFGFLAG.PACING_10MS | CFGFLAG.PACING_20MS EXTFLAG_UPDATE_MASK = ( EXTFLAG.SERIAL_BTN_VISIBLE | EXTFLAG.SERIAL_USB_VISIBLE | EXTFLAG.SERIAL_API_VISIBLE | EXTFLAG.USE_NUMERIC_KEYPAD | EXTFLAG.FAST_TRIG | EXTFLAG.ALLOW_UPDATE | EXTFLAG.DORMANT | EXTFLAG.LED_INV ) # Data sizes FIXED_SIZE = 16 UID_SIZE = 6 KEY_SIZE = 16 ACC_CODE_SIZE = 6 CONFIG_SIZE = 52 NDEF_DATA_SIZE = 54 HMAC_KEY_SIZE = 20 HMAC_CHALLENGE_SIZE = 64 HMAC_RESPONSE_SIZE = 20 SCAN_CODES_SIZE = FIXED_SIZE + UID_SIZE + KEY_SIZE SHA1_BLOCK_SIZE = 64 @unique class NDEF_TYPE(IntEnum): TEXT = ord("T") URI = ord("U") DEFAULT_NDEF_URI = "https://my.yubico.com/yk/#" NDEF_URL_PREFIXES = ( "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", "ftp://", "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", "sips:", "tftp:", "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", "file://", "urn:epc:id:", "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", "urn:nfc:", ) def _build_config(fixed, uid, key, ext, tkt, cfg, acc_code=None): buf = ( fixed.ljust(FIXED_SIZE, b"\0") + uid + key + (acc_code or b"\0" * ACC_CODE_SIZE) + struct.pack(">BBBB", len(fixed), ext, tkt, cfg) + b"\0\0" # RFU ) return buf + struct.pack("<H", 0xFFFF & ~calculate_crc(buf)) def _build_update(ext, tkt, cfg, acc_code=None): if ext & ~EXTFLAG_UPDATE_MASK != 0: raise ValueError("Unsupported ext flags for update") if tkt & ~TKTFLAG_UPDATE_MASK != 0: raise ValueError("Unsupported tkt flags for update") if cfg & ~CFGFLAG_UPDATE_MASK != 0: raise ValueError("Unsupported cfg flags for update") return _build_config( b"", b"\0" * UID_SIZE, b"\0" * KEY_SIZE, ext, tkt, cfg, acc_code ) def _build_ndef_config(value, ndef_type=NDEF_TYPE.URI): if ndef_type == NDEF_TYPE.URI: if value is None: value = DEFAULT_NDEF_URI for i, prefix in enumerate(NDEF_URL_PREFIXES): if value.startswith(prefix): id_code = i + 1 value = value[len(prefix) :] break else: id_code = 0 data = bytes([id_code]) + value.encode() else: if value is None: value = "" data = b"\x02en" + value.encode() if len(data) > NDEF_DATA_SIZE: raise ValueError("URI payload too large") return bytes([len(data), ndef_type]) + data.ljust(NDEF_DATA_SIZE, b"\0") @unique class CFGSTATE(IntFlag): # Bits in touch_level SLOT1_VALID = 0x01 # configuration 1 is valid (from firmware 2.1) SLOT2_VALID = 0x02 # configuration 2 is valid (from firmware 2.1) SLOT1_TOUCH = 0x04 # configuration 1 requires touch (from firmware 3.0) SLOT2_TOUCH = 0x08 # configuration 2 requires touch (from firmware 3.0) LED_INV = 0x10 # LED behavior is inverted (EXTFLAG_LED_INV mirror) def _shorten_hmac_key(key: bytes) -> bytes: if len(key) > SHA1_BLOCK_SIZE: key = sha1(key).digest() # nosec elif len(key) > HMAC_KEY_SIZE: raise NotSupportedError(f"Key lengths > {HMAC_KEY_SIZE} bytes not supported") return key Cfg = TypeVar("Cfg", bound="SlotConfiguration") class SlotConfiguration: def __init__(self): self._fixed = b"" self._uid = b"\0" * UID_SIZE self._key = b"\0" * KEY_SIZE self._flags = {} self._update_flags(EXTFLAG.SERIAL_API_VISIBLE, True) self._update_flags(EXTFLAG.ALLOW_UPDATE, True) def _update_flags(self, flag: IntFlag, value: bool) -> None: flag_key = type(flag) flags = self._flags.get(flag_key, 0) self._flags[flag_key] = flags | flag if value else flags & ~flag def is_supported_by(self, version: Version) -> bool: return True def get_config(self, acc_code: Optional[bytes] = None) -> bytes: return _build_config( self._fixed, self._uid, self._key, self._flags.get(EXTFLAG, 0), self._flags.get(TKTFLAG, 0), self._flags.get(CFGFLAG, 0), acc_code, ) def serial_api_visible(self: Cfg, value: bool) -> Cfg: self._update_flags(EXTFLAG.SERIAL_API_VISIBLE, value) return self def serial_usb_visible(self: Cfg, value: bool) -> Cfg: self._update_flags(EXTFLAG.SERIAL_USB_VISIBLE, value) return self def allow_update(self: Cfg, value: bool) -> Cfg: self._update_flags(EXTFLAG.ALLOW_UPDATE, value) return self def dormant(self: Cfg, value: bool) -> Cfg: self._update_flags(EXTFLAG.DORMANT, value) return self def invert_led(self: Cfg, value: bool) -> Cfg: self._update_flags(EXTFLAG.LED_INV, value) return self def protect_slot2(self: Cfg, value: bool) -> Cfg: self._update_flags(TKTFLAG.PROTECT_CFG2, value) return self class HmacSha1SlotConfiguration(SlotConfiguration): def __init__(self, key: bytes): super(HmacSha1SlotConfiguration, self).__init__() key = _shorten_hmac_key(key) # Key is packed into key and uid self._key = key[:KEY_SIZE].ljust(KEY_SIZE, b"\0") self._uid = key[KEY_SIZE:].ljust(UID_SIZE, b"\0") self._update_flags(TKTFLAG.CHAL_RESP, True) self._update_flags(CFGFLAG.CHAL_HMAC, True) self._update_flags(CFGFLAG.HMAC_LT64, True) def is_supported_by(self, version): return version >= (2, 2, 0) or version[0] == 0 def require_touch(self: Cfg, value: bool) -> Cfg: self._update_flags(CFGFLAG.CHAL_BTN_TRIG, value) return self def lt64(self: Cfg, value: bool) -> Cfg: self._update_flags(CFGFLAG.HMAC_LT64, value) return self class KeyboardSlotConfiguration(SlotConfiguration): def __init__(self): super(KeyboardSlotConfiguration, self).__init__() self._update_flags(TKTFLAG.APPEND_CR, True) self._update_flags(EXTFLAG.FAST_TRIG, True) def append_cr(self: Cfg, value: bool) -> Cfg: self._update_flags(TKTFLAG.APPEND_CR, value) return self def fast_trigger(self: Cfg, value: bool) -> Cfg: self._update_flags(EXTFLAG.FAST_TRIG, value) return self def pacing(self: Cfg, pacing_10ms: bool = False, pacing_20ms: bool = False) -> Cfg: self._update_flags(CFGFLAG.PACING_10MS, pacing_10ms) self._update_flags(CFGFLAG.PACING_20MS, pacing_20ms) return self def use_numeric(self: Cfg, value: bool) -> Cfg: self._update_flags(EXTFLAG.USE_NUMERIC_KEYPAD, value) return self class HotpSlotConfiguration(KeyboardSlotConfiguration): def __init__(self, key: bytes): super(HotpSlotConfiguration, self).__init__() key = _shorten_hmac_key(key) # Key is packed into key and uid self._key = key[:KEY_SIZE].ljust(KEY_SIZE, b"\0") self._uid = key[KEY_SIZE:].ljust(UID_SIZE, b"\0") self._update_flags(TKTFLAG.OATH_HOTP, True) self._update_flags(CFGFLAG.OATH_FIXED_MODHEX2, True) def is_supported_by(self, version): return version >= (2, 2, 0) or version[0] == 0 def digits8(self: Cfg, value: bool) -> Cfg: self._update_flags(CFGFLAG.OATH_HOTP8, value) return self def token_id( self: Cfg, token_id: bytes, fixed_modhex1: bool = False, fixed_modhex2: bool = True, ) -> Cfg: if len(token_id) > FIXED_SIZE: raise ValueError(f"token_id must be <= {FIXED_SIZE} bytes") self._fixed = token_id self._update_flags(CFGFLAG.OATH_FIXED_MODHEX1, fixed_modhex1) self._update_flags(CFGFLAG.OATH_FIXED_MODHEX2, fixed_modhex2) return self def imf(self: Cfg, imf: int) -> Cfg: if not (imf % 16 == 0 and 0 <= imf <= 0xFFFF0): raise ValueError( f"imf should be between {0} and {1048560}, evenly dividable by 16" ) self._uid = self._uid[:4] + struct.pack(">H", imf >> 4) return self class StaticPasswordSlotConfiguration(KeyboardSlotConfiguration): def __init__(self, scan_codes: bytes): super(StaticPasswordSlotConfiguration, self).__init__() if len(scan_codes) > SCAN_CODES_SIZE: raise NotSupportedError("Password is too long") # Scan codes are packed into fixed, uid, and key scan_codes = scan_codes.ljust(SCAN_CODES_SIZE, b"\0") self._fixed = scan_codes[:FIXED_SIZE] self._uid = scan_codes[FIXED_SIZE : FIXED_SIZE + UID_SIZE] self._key = scan_codes[FIXED_SIZE + UID_SIZE :] self._update_flags(CFGFLAG.SHORT_TICKET, True) def is_supported_by(self, version): return version >= (2, 2, 0) or version[0] == 0 class YubiOtpSlotConfiguration(KeyboardSlotConfiguration): def __init__(self, fixed: bytes, uid: bytes, key: bytes): super(YubiOtpSlotConfiguration, self).__init__() if len(fixed) > FIXED_SIZE: raise ValueError(f"fixed must be <= {FIXED_SIZE} bytes") if len(uid) != UID_SIZE: raise ValueError(f"uid must be {UID_SIZE} bytes") if len(key) != KEY_SIZE: raise ValueError(f"key must be {KEY_SIZE} bytes") self._fixed = fixed self._uid = uid self._key = key def tabs( self: Cfg, before: bool = False, after_first: bool = False, after_second: bool = False, ) -> Cfg: self._update_flags(TKTFLAG.TAB_FIRST, before) self._update_flags(TKTFLAG.APPEND_TAB1, after_first) self._update_flags(TKTFLAG.APPEND_TAB2, after_second) return self def delay(self: Cfg, after_first: bool = False, after_second: bool = False) -> Cfg: self._update_flags(TKTFLAG.APPEND_DELAY1, after_first) self._update_flags(TKTFLAG.APPEND_DELAY2, after_second) return self def send_reference(self: Cfg, value: bool) -> Cfg: self._update_flags(CFGFLAG.SEND_REF, value) return self class StaticTicketSlotConfiguration(KeyboardSlotConfiguration): def __init__(self, fixed: bytes, uid: bytes, key: bytes): super(StaticTicketSlotConfiguration, self).__init__() if len(fixed) > FIXED_SIZE: raise ValueError(f"fixed must be <= {FIXED_SIZE} bytes") if len(uid) != UID_SIZE: raise ValueError(f"uid must be {UID_SIZE} bytes") if len(key) != KEY_SIZE: raise ValueError(f"key must be {KEY_SIZE} bytes") self._fixed = fixed self._uid = uid self._key = key self._update_flags(CFGFLAG.STATIC_TICKET, True) def short_ticket(self: Cfg, value: bool) -> Cfg: self._update_flags(CFGFLAG.SHORT_TICKET, value) return self def strong_password( self: Cfg, upper_case: bool = False, digit: bool = False, special: bool = False ) -> Cfg: self._update_flags(CFGFLAG.STRONG_PW1, upper_case) self._update_flags(CFGFLAG.STRONG_PW2, digit or special) self._update_flags(CFGFLAG.SEND_REF, special) return self def manual_update(self: Cfg, value: bool) -> Cfg: self._update_flags(CFGFLAG.MAN_UPDATE, value) return self class UpdateConfiguration(KeyboardSlotConfiguration): def __init__(self): super(UpdateConfiguration, self).__init__() self._fixed = b"\0" * FIXED_SIZE self._uid = b"\0" * UID_SIZE self._key = b"\0" * KEY_SIZE def is_supported_by(self, version): return version >= (2, 2, 0) or version[0] == 0 def _update_flags(self, flag, value): # NB: All EXT flags are allowed if isinstance(flag, TKTFLAG): if not TKTFLAG_UPDATE_MASK & flag: raise ValueError("Unsupported TKT flag for update") elif isinstance(flag, CFGFLAG): if not CFGFLAG_UPDATE_MASK & flag: raise ValueError("Unsupported CFG flag for update") super(UpdateConfiguration, self)._update_flags(flag, value) def protect_slot2(self: Cfg, value): raise ValueError("protect_slot2 cannot be applied to UpdateConfiguration") def tabs( self: Cfg, before: bool = False, after_first: bool = False, after_second: bool = False, ) -> Cfg: self._update_flags(TKTFLAG.TAB_FIRST, before) self._update_flags(TKTFLAG.APPEND_TAB1, after_first) self._update_flags(TKTFLAG.APPEND_TAB2, after_second) return self def delay(self: Cfg, after_first: bool = False, after_second: bool = False) -> Cfg: self._update_flags(TKTFLAG.APPEND_DELAY1, after_first) self._update_flags(TKTFLAG.APPEND_DELAY2, after_second) return self class ConfigState: """The configuration state of the YubiOTP application.""" def __init__(self, version: Version, touch_level: int): self.version = version self.flags = sum(CFGSTATE) & touch_level def is_configured(self, slot: SLOT) -> bool: """Checks of a slot is programmed, or empty""" require_version(self.version, (2, 1, 0)) return self.flags & (CFGSTATE.SLOT1_VALID, CFGSTATE.SLOT2_VALID)[slot - 1] != 0 def is_touch_triggered(self, slot: SLOT) -> bool: """Checks if a (programmed) state is triggered by touch (not challenge-response) Requires YubiKey 3 or later. """ require_version(self.version, (3, 0, 0)) return self.flags & (CFGSTATE.SLOT1_TOUCH, CFGSTATE.SLOT2_TOUCH)[slot - 1] != 0 def is_led_inverted(self) -> bool: """Checks if the LED behavior is inverted.""" return self.flags & CFGSTATE.LED_INV != 0 def __repr__(self): items = [] try: items.append( "configured: (%s, %s)" % (self.is_configured(SLOT.ONE), self.is_configured(SLOT.TWO)) ) items.append( "touch_triggered: (%s, %s)" % (self.is_touch_triggered(SLOT.ONE), self.is_touch_triggered(SLOT.TWO)) ) items.append("led_inverted: %s" % self.is_led_inverted()) except NotSupportedError: pass return f"ConfigState({', '.join(items)})" class _Backend(abc.ABC): version: Version @abc.abstractmethod def close(self) -> None: ... @abc.abstractmethod def write_update(self, slot: CONFIG_SLOT, data: bytes) -> bytes: ... @abc.abstractmethod def send_and_receive( self, slot: CONFIG_SLOT, data: bytes, expected_len: int, event: Optional[Event] = None, on_keepalive: Optional[Callable[[int], None]] = None, ) -> bytes: ... class _YubiOtpOtpBackend(_Backend): def __init__(self, protocol): self.protocol = protocol def close(self): self.protocol.close() def write_update(self, slot, data): return self.protocol.send_and_receive(slot, data) def send_and_receive(self, slot, data, expected_len, event=None, on_keepalive=None): response = self.protocol.send_and_receive(slot, data, event, on_keepalive) if check_crc(response[: expected_len + 2]): return response[:expected_len] raise BadResponseError("Invalid CRC") INS_CONFIG = 0x01 class _YubiOtpSmartCardBackend(_Backend): def __init__(self, protocol, version, prog_seq): self.protocol = protocol self._version = version self._prog_seq = prog_seq def close(self): self.protocol.close() def write_update(self, slot, data): status = self.protocol.send_apdu(0, INS_CONFIG, slot, 0, data) prev_prog_seq, self._prog_seq = self._prog_seq, status[3] if self._prog_seq == prev_prog_seq + 1: return status if self._prog_seq == 0 and prev_prog_seq > 0: version = Version.from_bytes(status[:3]) if (4, 0) <= version < (5, 5): # Programming state does not update return status if status[4] & 0x1F == 0: return status raise CommandRejectedError("Not updated") def send_and_receive(self, slot, data, expected_len, event=None, on_keepalive=None): response = self.protocol.send_apdu(0, INS_CONFIG, slot, 0, data) if expected_len == len(response): return response raise BadResponseError("Unexpected response length") class YubiOtpSession: """A session with the YubiOTP application.""" def __init__(self, connection: Union[OtpConnection, SmartCardConnection]): if isinstance(connection, OtpConnection): otp_protocol = OtpProtocol(connection) self._status = otp_protocol.read_status() self._version = otp_protocol.version self.backend: _Backend = _YubiOtpOtpBackend(otp_protocol) elif isinstance(connection, SmartCardConnection): card_protocol = SmartCardProtocol(connection) mgmt_version = None if connection.transport == TRANSPORT.NFC: # This version is more reliable over NFC try: card_protocol.select(AID.MANAGEMENT) select_str = card_protocol.select(AID.MANAGEMENT).decode() mgmt_version = Version.from_string(select_str) except ApplicationNotAvailableError: pass # Not available (probably NEO), get version from status self._status = card_protocol.select(AID.OTP) otp_version = Version.from_bytes(self._status[:3]) if mgmt_version and mgmt_version[0] == 3: # NEO reports the highest of these two self._version = max(mgmt_version, otp_version) else: self._version = mgmt_version or otp_version card_protocol.enable_touch_workaround(self._version) self.backend = _YubiOtpSmartCardBackend( card_protocol, self._version, self._status[3] ) else: raise TypeError("Unsupported connection type") logger.debug( "YubiOTP session initialized for " f"connection={type(connection).__name__}, version={self.version}, " f"state={self.get_config_state()}" ) def close(self) -> None: self.backend.close() @property def version(self) -> Version: return self._version def get_serial(self) -> int: """Get serial number.""" return bytes2int( self.backend.send_and_receive(CONFIG_SLOT.DEVICE_SERIAL, b"", 4) ) def get_config_state(self) -> ConfigState: """Get configuration state of the YubiOTP application.""" return ConfigState(self.version, struct.unpack("<H", self._status[4:6])[0]) def _write_config(self, slot, config, cur_acc_code): has_acc = bool(cur_acc_code) logger.debug(f"Writing configuration to slot {slot}, access code: {has_acc}") self._status = self.backend.write_update( slot, config + (cur_acc_code or b"\0" * ACC_CODE_SIZE) ) logger.info("Configuration written") def put_configuration( self, slot: SLOT, configuration: SlotConfiguration, acc_code: Optional[bytes] = None, cur_acc_code: Optional[bytes] = None, ) -> None: """Write configuration to slot. :param slot: The slot to configure. :param configuration: The slot configuration. :param acc_code: The new access code. :param cur_acc_code: The current access code. """ if not configuration.is_supported_by(self.version): raise NotSupportedError( "This configuration is not supported on this YubiKey version" ) slot = SLOT(slot) logger.debug( f"Writing configuration of type {type(configuration).__name__} to " f"slot {slot}" ) self._write_config( SLOT.map(slot, CONFIG_SLOT.CONFIG_1, CONFIG_SLOT.CONFIG_2), configuration.get_config(acc_code), cur_acc_code, ) def update_configuration( self, slot: SLOT, configuration: SlotConfiguration, acc_code: Optional[bytes] = None, cur_acc_code: Optional[bytes] = None, ) -> None: """Update configuration in slot. :param slot: The slot to update the configuration in. :param configuration: The slot configuration. :param acc_code: The new access code. :param cur_acc_code: The current access code. """ if not configuration.is_supported_by(self.version): raise NotSupportedError( "This configuration is not supported on this YubiKey version" ) if acc_code != cur_acc_code and (4, 3, 2) <= self.version < (4, 3, 6): raise NotSupportedError( "The access code cannot be updated on this YubiKey. " "Instead, delete the slot and configure it anew." ) slot = SLOT(slot) logger.debug(f"Writing configuration update to slot {slot}") self._write_config( SLOT.map(slot, CONFIG_SLOT.UPDATE_1, CONFIG_SLOT.UPDATE_2), configuration.get_config(acc_code), cur_acc_code, ) def swap_slots(self) -> None: """Swap the two slot configurations.""" logger.debug("Swapping touch slots") self._write_config(CONFIG_SLOT.SWAP, b"", None) def delete_slot(self, slot: SLOT, cur_acc_code: Optional[bytes] = None) -> None: """Delete configuration stored in slot. :param slot: The slot to delete the configuration in. :param cur_acc_code: The current access code. """ slot = SLOT(slot) logger.debug(f"Deleting slot {slot}") self._write_config( SLOT.map(slot, CONFIG_SLOT.CONFIG_1, CONFIG_SLOT.CONFIG_2), b"\0" * CONFIG_SIZE, cur_acc_code, ) def set_scan_map( self, scan_map: bytes, cur_acc_code: Optional[bytes] = None ) -> None: """Update scan-codes on YubiKey. This updates the scan-codes (or keyboard presses) that the YubiKey will use when typing out OTPs. """ logger.debug("Writing scan map") self._write_config(CONFIG_SLOT.SCAN_MAP, scan_map, cur_acc_code) def set_ndef_configuration( self, slot: SLOT, uri: Optional[str] = None, cur_acc_code: Optional[bytes] = None, ndef_type: NDEF_TYPE = NDEF_TYPE.URI, ) -> None: """Configure a slot to be used over NDEF (NFC). :param slot: The slot to configure. :param uri: URI or static text. :param cur_acc_code: The current access code. :param ndef_type: The NDEF type (text or URI). """ slot = SLOT(slot) logger.debug(f"Writing NDEF configuration for slot {slot} of type {ndef_type}") self._write_config( SLOT.map(slot, CONFIG_SLOT.NDEF_1, CONFIG_SLOT.NDEF_2), _build_ndef_config(uri, ndef_type), cur_acc_code, ) def calculate_hmac_sha1( self, slot: SLOT, challenge: bytes, event: Optional[Event] = None, on_keepalive: Optional[Callable[[int], None]] = None, ) -> bytes: """Perform a challenge-response operation using HMAC-SHA1. :param slot: The slot to perform the operation against. :param challenge: The challenge. :param event: An event. """ require_version(self.version, (2, 2, 0)) slot = SLOT(slot) logger.debug(f"Calculating response for slot {slot}") # Pad challenge with byte different from last challenge = challenge.ljust( HMAC_CHALLENGE_SIZE, b"\1" if challenge.endswith(b"\0") else b"\0" ) return self.backend.send_and_receive( SLOT.map(slot, CONFIG_SLOT.CHAL_HMAC_1, CONFIG_SLOT.CHAL_HMAC_2), challenge, HMAC_RESPONSE_SIZE, event, on_keepalive, )
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/yubiotp.py
yubiotp.py
from .core import ( TRANSPORT, YUBIKEY, PID, Version, Connection, NotSupportedError, ApplicationNotAvailableError, ) from .core.otp import OtpConnection, CommandRejectedError from .core.fido import FidoConnection from .core.smartcard import ( AID, SmartCardConnection, SmartCardProtocol, ) from .management import ( ManagementSession, DeviceInfo, DeviceConfig, Mode, USB_INTERFACE, CAPABILITY, FORM_FACTOR, DEVICE_FLAG, ) from .yubiotp import YubiOtpSession from time import sleep from typing import Optional import logging logger = logging.getLogger(__name__) # Old U2F AID, only used to detect the presence of the applet _AID_U2F_YUBICO = bytes.fromhex("a0000005271002") _SCAN_APPLETS = ( # OTP will be checked elsewhere and thus isn't needed here (AID.FIDO, CAPABILITY.U2F), (_AID_U2F_YUBICO, CAPABILITY.U2F), (AID.PIV, CAPABILITY.PIV), (AID.OPENPGP, CAPABILITY.OPENPGP), (AID.OATH, CAPABILITY.OATH), ) _BASE_NEO_APPS = CAPABILITY.OTP | CAPABILITY.OATH | CAPABILITY.PIV | CAPABILITY.OPENPGP def _read_info_ccid(conn, key_type, interfaces): version: Optional[Version] = None try: mgmt = ManagementSession(conn) version = mgmt.version try: return mgmt.read_device_info() except NotSupportedError: # Workaround to "de-select" the Management Applet needed for NEO conn.send_and_receive(b"\xa4\x04\x00\x08") except ApplicationNotAvailableError: logger.debug("Couldn't select Management application, use fallback") # Synthesize data capabilities = CAPABILITY(0) # Try to read serial (and version if needed) from OTP application serial = None try: otp = YubiOtpSession(conn) if version is None: version = otp.version try: serial = otp.get_serial() except Exception: logger.debug("Unable to read serial over OTP, no serial", exc_info=True) capabilities |= CAPABILITY.OTP except ApplicationNotAvailableError: logger.debug("Couldn't select OTP application, serial unknown") if version is None: logger.debug("Firmware version unknown, using 3.0.0 as a baseline") version = Version(3, 0, 0) # Guess, no way to know # Scan for remaining capabilities logger.debug("Scan for available applications...") protocol = SmartCardProtocol(conn) for aid, code in _SCAN_APPLETS: try: protocol.select(aid) capabilities |= code logger.debug("Found applet: aid: %s, capability: %s", aid, code) except ApplicationNotAvailableError: logger.debug("Missing applet: aid: %s, capability: %s", aid, code) except Exception: logger.warning( "Error selecting aid: %s, capability: %s", aid, code, exc_info=True ) if not capabilities and not key_type: # NFC, no capabilities, probably not a YubiKey. raise ValueError("Device does not seem to be a YubiKey") # Assume U2F on devices >= 3.3.0 if USB_INTERFACE.FIDO in interfaces or version >= (3, 3, 0): capabilities |= CAPABILITY.U2F return DeviceInfo( config=DeviceConfig( enabled_capabilities={}, # Populated later auto_eject_timeout=0, challenge_response_timeout=0, device_flags=DEVICE_FLAG(0), ), serial=serial, version=version, form_factor=FORM_FACTOR.UNKNOWN, supported_capabilities={ TRANSPORT.USB: capabilities, TRANSPORT.NFC: capabilities, }, is_locked=False, ) def _read_info_otp(conn, key_type, interfaces): otp = None serial = None try: mgmt = ManagementSession(conn) except ApplicationNotAvailableError: otp = YubiOtpSession(conn) # Retry during potential reclaim timeout period (~3s). for _ in range(8): try: if otp is None: try: return mgmt.read_device_info() # Rejected while reclaim except NotSupportedError: otp = YubiOtpSession(conn) serial = otp.get_serial() # Rejected if reclaim (or not API_SERIAL_VISIBLE) break except CommandRejectedError: if otp and interfaces == USB_INTERFACE.OTP: break # Can't be reclaim with only one interface logger.debug("Potential reclaim, sleep...", exc_info=True) sleep(0.5) # Potential reclaim else: otp = YubiOtpSession(conn) # Synthesize info logger.debug("Unable to get info via Management application, use fallback") version = otp.version if key_type == YUBIKEY.NEO: usb_supported = _BASE_NEO_APPS if USB_INTERFACE.FIDO in interfaces or version >= (3, 3, 0): usb_supported |= CAPABILITY.U2F capabilities = { TRANSPORT.USB: usb_supported, TRANSPORT.NFC: usb_supported, } elif key_type == YUBIKEY.YKP: capabilities = { TRANSPORT.USB: CAPABILITY.OTP | CAPABILITY.U2F, } else: capabilities = { TRANSPORT.USB: CAPABILITY.OTP, } return DeviceInfo( config=DeviceConfig( enabled_capabilities={}, # Populated later auto_eject_timeout=0, challenge_response_timeout=0, device_flags=DEVICE_FLAG(0), ), serial=serial, version=version, form_factor=FORM_FACTOR.UNKNOWN, supported_capabilities=capabilities.copy(), is_locked=False, ) def _read_info_ctap(conn, key_type, interfaces): try: mgmt = ManagementSession(conn) return mgmt.read_device_info() except Exception: # SKY 1, NEO, or YKP logger.debug("Unable to get info via Management application, use fallback") # Best guess version if key_type == YUBIKEY.YKP: version = Version(4, 0, 0) else: version = Version(3, 0, 0) supported_apps = {TRANSPORT.USB: CAPABILITY.U2F} if key_type == YUBIKEY.NEO: supported_apps[TRANSPORT.USB] |= _BASE_NEO_APPS supported_apps[TRANSPORT.NFC] = supported_apps[TRANSPORT.USB] return DeviceInfo( config=DeviceConfig( enabled_capabilities={}, # Populated later auto_eject_timeout=0, challenge_response_timeout=0, device_flags=DEVICE_FLAG(0), ), serial=None, version=version, form_factor=FORM_FACTOR.USB_A_KEYCHAIN, supported_capabilities=supported_apps, is_locked=False, ) def read_info(conn: Connection, pid: Optional[PID] = None) -> DeviceInfo: """Reads out DeviceInfo from a YubiKey, or attempts to synthesize the data. Reading DeviceInfo from a ManagementSession is only supported for newer YubiKeys. This function attempts to read that information, but will fall back to gathering the data using other mechanisms if needed. It will also make adjustments to the data if required, for example to "fix" known bad values. The *pid* parameter must be provided whenever the YubiKey is connected via USB. :param conn: A connection to a YubiKey. :param pid: The USB Product ID. """ logger.debug(f"Attempting to read device info, using {type(conn).__name__}") if pid: key_type: Optional[YUBIKEY] = pid.yubikey_type interfaces = pid.usb_interfaces elif isinstance(conn, SmartCardConnection) and conn.transport == TRANSPORT.NFC: # No PID for NFC connections key_type = None interfaces = USB_INTERFACE(0) # Add interfaces later # For NEO we need to figure out the mode, newer keys get it from Management protocol = SmartCardProtocol(conn) try: resp = protocol.select(AID.OTP) if resp[0] == 3 and len(resp) > 6: interfaces = Mode.from_code(resp[6]).interfaces except ApplicationNotAvailableError: pass # OTP turned off, this must be YK5, no problem else: raise ValueError("PID must be provided for non-NFC connections") if isinstance(conn, SmartCardConnection): info = _read_info_ccid(conn, key_type, interfaces) elif isinstance(conn, OtpConnection): info = _read_info_otp(conn, key_type, interfaces) elif isinstance(conn, FidoConnection): info = _read_info_ctap(conn, key_type, interfaces) else: raise TypeError("Invalid connection type") logger.debug("Read info: %s", info) # Set usb_enabled if missing (pre YubiKey 5) if ( info.has_transport(TRANSPORT.USB) and TRANSPORT.USB not in info.config.enabled_capabilities ): usb_enabled = info.supported_capabilities[TRANSPORT.USB] if usb_enabled == (CAPABILITY.OTP | CAPABILITY.U2F | USB_INTERFACE.CCID): # YubiKey Edge, hide unusable CCID interface from supported # usb_enabled = CAPABILITY.OTP | CAPABILITY.U2F info.supported_capabilities = { TRANSPORT.USB: CAPABILITY.OTP | CAPABILITY.U2F } if USB_INTERFACE.OTP not in interfaces: usb_enabled &= ~CAPABILITY.OTP if USB_INTERFACE.FIDO not in interfaces: usb_enabled &= ~(CAPABILITY.U2F | CAPABILITY.FIDO2) if USB_INTERFACE.CCID not in interfaces: usb_enabled &= ~( USB_INTERFACE.CCID | CAPABILITY.OATH | CAPABILITY.OPENPGP | CAPABILITY.PIV ) info.config.enabled_capabilities[TRANSPORT.USB] = usb_enabled # SKY identified by PID if key_type == YUBIKEY.SKY: info.is_sky = True # YK4-based FIPS version if (4, 4, 0) <= info.version < (4, 5, 0): info.is_fips = True # Set nfc_enabled if missing (pre YubiKey 5) if ( info.has_transport(TRANSPORT.NFC) and TRANSPORT.NFC not in info.config.enabled_capabilities ): info.config.enabled_capabilities[TRANSPORT.NFC] = info.supported_capabilities[ TRANSPORT.NFC ] # Workaround for invalid configurations. if info.version >= (4, 0, 0): if info.form_factor in ( FORM_FACTOR.USB_A_NANO, FORM_FACTOR.USB_C_NANO, FORM_FACTOR.USB_C_LIGHTNING, ) or ( info.form_factor is FORM_FACTOR.USB_C_KEYCHAIN and info.version < (5, 2, 4) ): # Known not to have NFC info.supported_capabilities.pop(TRANSPORT.NFC, None) info.config.enabled_capabilities.pop(TRANSPORT.NFC, None) logger.debug("Device info, after tweaks: %s", info) return info def _fido_only(capabilities): return capabilities & ~(CAPABILITY.U2F | CAPABILITY.FIDO2) == 0 def _is_preview(version): _PREVIEW_RANGES = ( ((5, 0, 0), (5, 1, 0)), ((5, 2, 0), (5, 2, 3)), ((5, 5, 0), (5, 5, 2)), ) for start, end in _PREVIEW_RANGES: if start <= version < end: return True return False def get_name(info: DeviceInfo, key_type: Optional[YUBIKEY]) -> str: """Determine the product name of a YubiKey :param info: The device info. :param key_type: The YubiKey hardware platform. """ usb_supported = info.supported_capabilities[TRANSPORT.USB] # Guess the key type (over NFC) if not key_type: if info.version[0] == 3: key_type = YUBIKEY.NEO elif info.serial is None and _fido_only(usb_supported): key_type = YUBIKEY.SKY if info.version < (5, 2, 8) else YUBIKEY.YK4 else: key_type = YUBIKEY.YK4 # Generic name based on key type alone device_name = key_type.value # Improved name based on configuration if key_type == YUBIKEY.SKY: if CAPABILITY.FIDO2 not in usb_supported: device_name = "FIDO U2F Security Key" # SKY 1 if info.has_transport(TRANSPORT.NFC): device_name = "Security Key NFC" elif key_type == YUBIKEY.YK4: major_version = info.version[0] if major_version < 4: if info.version[0] == 0: return f"YubiKey ({info.version})" else: return "YubiKey" elif major_version == 4: if info.is_fips: device_name = "YubiKey FIPS" elif usb_supported == CAPABILITY.OTP | CAPABILITY.U2F: device_name = "YubiKey Edge" else: device_name = "YubiKey 4" if _is_preview(info.version): device_name = "YubiKey Preview" elif info.version >= (5, 1, 0): # Dynamic name building for YK5 is_nano = info.form_factor in ( FORM_FACTOR.USB_A_NANO, FORM_FACTOR.USB_C_NANO, ) is_bio = info.form_factor in (FORM_FACTOR.USB_A_BIO, FORM_FACTOR.USB_C_BIO) is_c = info.form_factor in ( # Does NOT include Ci FORM_FACTOR.USB_C_KEYCHAIN, FORM_FACTOR.USB_C_NANO, FORM_FACTOR.USB_C_BIO, ) if info.is_sky: name_parts = ["Security Key"] else: name_parts = ["YubiKey"] if not is_bio: name_parts.append("5") if is_c: name_parts.append("C") elif info.form_factor == FORM_FACTOR.USB_C_LIGHTNING: name_parts.append("Ci") if is_nano: name_parts.append("Nano") if info.has_transport(TRANSPORT.NFC): name_parts.append("NFC") elif info.form_factor == FORM_FACTOR.USB_A_KEYCHAIN: name_parts.append("A") # Only for non-NFC A Keychain. if is_bio: name_parts.append("Bio") if _fido_only(usb_supported): name_parts.append("- FIDO Edition") if info.is_fips: name_parts.append("FIPS") if info.is_sky and info.serial: name_parts.append("- Enterprise Edition") device_name = " ".join(name_parts).replace("5 C", "5C").replace("5 A", "5A") return device_name
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/support.py
support.py
from .core import ( bytes2int, int2bytes, require_version, Version, Tlv, TRANSPORT, USB_INTERFACE, NotSupportedError, BadResponseError, ApplicationNotAvailableError, ) from .core.otp import ( check_crc, OtpConnection, OtpProtocol, STATUS_OFFSET_PROG_SEQ, CommandRejectedError, ) from .core.fido import FidoConnection from .core.smartcard import AID, SmartCardConnection, SmartCardProtocol from fido2.hid import CAPABILITY as CTAP_CAPABILITY from enum import IntEnum, IntFlag, unique from dataclasses import dataclass from typing import Optional, Union, Mapping import abc import struct import logging logger = logging.getLogger(__name__) @unique class CAPABILITY(IntFlag): """YubiKey Application identifiers.""" OTP = 0x01 U2F = 0x02 FIDO2 = 0x200 OATH = 0x20 PIV = 0x10 OPENPGP = 0x08 HSMAUTH = 0x100 def __str__(self): name = "|".join(c.name or str(c) for c in CAPABILITY if c in self) return f"{name}: {hex(self)}" @property def display_name(self): if self == CAPABILITY.U2F: return "FIDO U2F" elif self == CAPABILITY.OPENPGP: return "OpenPGP" elif self == CAPABILITY.HSMAUTH: return "YubiHSM Auth" return self.name or ", ".join(c.display_name for c in CAPABILITY if c in self) @property def usb_interfaces(self) -> USB_INTERFACE: ifaces = USB_INTERFACE(0) if self & CAPABILITY.OTP: ifaces |= USB_INTERFACE.OTP if self & (CAPABILITY.U2F | CAPABILITY.FIDO2): ifaces |= USB_INTERFACE.FIDO if self & ( CAPABILITY.OATH | CAPABILITY.PIV | CAPABILITY.OPENPGP | CAPABILITY.HSMAUTH ): ifaces |= USB_INTERFACE.CCID return ifaces @unique class FORM_FACTOR(IntEnum): """YubiKey device form factors.""" UNKNOWN = 0x00 USB_A_KEYCHAIN = 0x01 USB_A_NANO = 0x02 USB_C_KEYCHAIN = 0x03 USB_C_NANO = 0x04 USB_C_LIGHTNING = 0x05 USB_A_BIO = 0x06 USB_C_BIO = 0x07 def __str__(self): if self == FORM_FACTOR.USB_A_KEYCHAIN: return "Keychain (USB-A)" elif self == FORM_FACTOR.USB_A_NANO: return "Nano (USB-A)" elif self == FORM_FACTOR.USB_C_KEYCHAIN: return "Keychain (USB-C)" elif self == FORM_FACTOR.USB_C_NANO: return "Nano (USB-C)" elif self == FORM_FACTOR.USB_C_LIGHTNING: return "Keychain (USB-C, Lightning)" elif self == FORM_FACTOR.USB_A_BIO: return "Bio (USB-A)" elif self == FORM_FACTOR.USB_C_BIO: return "Bio (USB-C)" else: return "Unknown" @classmethod def from_code(cls, code: int) -> "FORM_FACTOR": if code and not isinstance(code, int): raise ValueError(f"Invalid form factor code: {code}") code &= 0xF return cls(code) if code in cls.__members__.values() else cls.UNKNOWN @unique class DEVICE_FLAG(IntFlag): """Configuration flags.""" REMOTE_WAKEUP = 0x40 EJECT = 0x80 TAG_USB_SUPPORTED = 0x01 TAG_SERIAL = 0x02 TAG_USB_ENABLED = 0x03 TAG_FORM_FACTOR = 0x04 TAG_VERSION = 0x05 TAG_AUTO_EJECT_TIMEOUT = 0x06 TAG_CHALRESP_TIMEOUT = 0x07 TAG_DEVICE_FLAGS = 0x08 TAG_APP_VERSIONS = 0x09 TAG_CONFIG_LOCK = 0x0A TAG_UNLOCK = 0x0B TAG_REBOOT = 0x0C TAG_NFC_SUPPORTED = 0x0D TAG_NFC_ENABLED = 0x0E @dataclass class DeviceConfig: """Management settings for YubiKey which can be configured by the user.""" enabled_capabilities: Mapping[TRANSPORT, CAPABILITY] auto_eject_timeout: Optional[int] challenge_response_timeout: Optional[int] device_flags: Optional[DEVICE_FLAG] def get_bytes( self, reboot: bool, cur_lock_code: Optional[bytes] = None, new_lock_code: Optional[bytes] = None, ) -> bytes: buf = b"" if reboot: buf += Tlv(TAG_REBOOT) if cur_lock_code: buf += Tlv(TAG_UNLOCK, cur_lock_code) usb_enabled = self.enabled_capabilities.get(TRANSPORT.USB) if usb_enabled is not None: buf += Tlv(TAG_USB_ENABLED, int2bytes(usb_enabled, 2)) nfc_enabled = self.enabled_capabilities.get(TRANSPORT.NFC) if nfc_enabled is not None: buf += Tlv(TAG_NFC_ENABLED, int2bytes(nfc_enabled, 2)) if self.auto_eject_timeout is not None: buf += Tlv(TAG_AUTO_EJECT_TIMEOUT, int2bytes(self.auto_eject_timeout, 2)) if self.challenge_response_timeout is not None: buf += Tlv(TAG_CHALRESP_TIMEOUT, int2bytes(self.challenge_response_timeout)) if self.device_flags is not None: buf += Tlv(TAG_DEVICE_FLAGS, int2bytes(self.device_flags)) if new_lock_code: buf += Tlv(TAG_CONFIG_LOCK, new_lock_code) if len(buf) > 0xFF: raise NotSupportedError("DeviceConfiguration too large") return int2bytes(len(buf)) + buf @dataclass class DeviceInfo: """Information about a YubiKey readable using the ManagementSession.""" config: DeviceConfig serial: Optional[int] version: Version form_factor: FORM_FACTOR supported_capabilities: Mapping[TRANSPORT, CAPABILITY] is_locked: bool is_fips: bool = False is_sky: bool = False def has_transport(self, transport: TRANSPORT) -> bool: return transport in self.supported_capabilities @classmethod def parse(cls, encoded: bytes, default_version: Version) -> "DeviceInfo": if len(encoded) - 1 != encoded[0]: raise BadResponseError("Invalid length") data = Tlv.parse_dict(encoded[1:]) locked = data.get(TAG_CONFIG_LOCK) == b"\1" serial = bytes2int(data.get(TAG_SERIAL, b"\0")) or None ff_value = bytes2int(data.get(TAG_FORM_FACTOR, b"\0")) form_factor = FORM_FACTOR.from_code(ff_value) fips = bool(ff_value & 0x80) sky = bool(ff_value & 0x40) if TAG_VERSION in data: version = Version.from_bytes(data[TAG_VERSION]) else: version = default_version auto_eject_to = bytes2int(data.get(TAG_AUTO_EJECT_TIMEOUT, b"\0")) chal_resp_to = bytes2int(data.get(TAG_CHALRESP_TIMEOUT, b"\0")) flags = DEVICE_FLAG(bytes2int(data.get(TAG_DEVICE_FLAGS, b"\0"))) supported = {} enabled = {} if version == (4, 2, 4): # Doesn't report correctly supported[TRANSPORT.USB] = CAPABILITY(0x3F) else: supported[TRANSPORT.USB] = CAPABILITY(bytes2int(data[TAG_USB_SUPPORTED])) if TAG_USB_ENABLED in data: # From YK 5.0.0 if not ((4, 0, 0) <= version < (5, 0, 0)): # Broken on YK4 enabled[TRANSPORT.USB] = CAPABILITY(bytes2int(data[TAG_USB_ENABLED])) if TAG_NFC_SUPPORTED in data: # YK with NFC supported[TRANSPORT.NFC] = CAPABILITY(bytes2int(data[TAG_NFC_SUPPORTED])) enabled[TRANSPORT.NFC] = CAPABILITY(bytes2int(data[TAG_NFC_ENABLED])) return cls( DeviceConfig(enabled, auto_eject_to, chal_resp_to, flags), serial, version, form_factor, supported, locked, fips, sky, ) _MODES = [ USB_INTERFACE.OTP, # 0x00 USB_INTERFACE.CCID, # 0x01 USB_INTERFACE.OTP | USB_INTERFACE.CCID, # 0x02 USB_INTERFACE.FIDO, # 0x03 USB_INTERFACE.OTP | USB_INTERFACE.FIDO, # 0x04 USB_INTERFACE.FIDO | USB_INTERFACE.CCID, # 0x05 USB_INTERFACE.OTP | USB_INTERFACE.FIDO | USB_INTERFACE.CCID, # 0x06 ] @dataclass(init=False, repr=False) class Mode: """YubiKey USB Mode configuration for use with YubiKey NEO and 4.""" code: int interfaces: USB_INTERFACE def __init__(self, interfaces: USB_INTERFACE): try: self.code = _MODES.index(interfaces) self.interfaces = USB_INTERFACE(interfaces) except ValueError: raise ValueError("Invalid mode!") def __repr__(self): return "+".join(t.name or str(t) for t in USB_INTERFACE if t in self.interfaces) @classmethod def from_code(cls, code: int) -> "Mode": # Mode is determined from the lowest 3 bits try: return cls(_MODES[code & 0b00000111]) except IndexError: raise ValueError("Invalid mode code") SLOT_DEVICE_CONFIG = 0x11 SLOT_YK4_CAPABILITIES = 0x13 SLOT_YK4_SET_DEVICE_INFO = 0x15 class _Backend(abc.ABC): version: Version @abc.abstractmethod def close(self) -> None: ... @abc.abstractmethod def set_mode(self, data: bytes) -> None: ... @abc.abstractmethod def read_config(self) -> bytes: ... @abc.abstractmethod def write_config(self, config: bytes) -> None: ... class _ManagementOtpBackend(_Backend): def __init__(self, otp_connection): self.protocol = OtpProtocol(otp_connection) self.version = self.protocol.version if (1, 0, 0) <= self.version < (3, 0, 0): raise ApplicationNotAvailableError() def close(self): self.protocol.close() def set_mode(self, data): empty = self.protocol.read_status()[STATUS_OFFSET_PROG_SEQ] == 0 try: self.protocol.send_and_receive(SLOT_DEVICE_CONFIG, data) except CommandRejectedError: if empty: return # ProgSeq isn't updated by set mode when empty raise def read_config(self): response = self.protocol.send_and_receive(SLOT_YK4_CAPABILITIES) r_len = response[0] if check_crc(response[: r_len + 1 + 2]): return response[: r_len + 1] raise BadResponseError("Invalid checksum") def write_config(self, config): self.protocol.send_and_receive(SLOT_YK4_SET_DEVICE_INFO, config) INS_READ_CONFIG = 0x1D INS_WRITE_CONFIG = 0x1C INS_SET_MODE = 0x16 P1_DEVICE_CONFIG = 0x11 class _ManagementSmartCardBackend(_Backend): def __init__(self, smartcard_connection): self.protocol = SmartCardProtocol(smartcard_connection) try: select_bytes = self.protocol.select(AID.MANAGEMENT) if select_bytes[-2:] == b"\x90\x00": # YubiKey Edge incorrectly appends SW twice. select_bytes = select_bytes[:-2] select_str = select_bytes.decode() self.version = Version.from_string(select_str) # For YubiKey NEO, we use the OTP application for further commands if self.version[0] == 3: # Workaround to "de-select" on NEO, otherwise it gets stuck. self.protocol.connection.send_and_receive(b"\xa4\x04\x00\x08") self.protocol.select(AID.OTP) except ApplicationNotAvailableError: if smartcard_connection.transport == TRANSPORT.NFC: # Probably NEO over NFC status = self.protocol.select(AID.OTP) self.version = Version.from_bytes(status[:3]) else: raise def close(self): self.protocol.close() def set_mode(self, data): if self.version[0] == 3: # Using the OTP application self.protocol.send_apdu(0, 0x01, SLOT_DEVICE_CONFIG, 0, data) else: self.protocol.send_apdu(0, INS_SET_MODE, P1_DEVICE_CONFIG, 0, data) def read_config(self): return self.protocol.send_apdu(0, INS_READ_CONFIG, 0, 0) def write_config(self, config): self.protocol.send_apdu(0, INS_WRITE_CONFIG, 0, 0, config) CTAP_VENDOR_FIRST = 0x40 CTAP_YUBIKEY_DEVICE_CONFIG = CTAP_VENDOR_FIRST CTAP_READ_CONFIG = CTAP_VENDOR_FIRST + 2 CTAP_WRITE_CONFIG = CTAP_VENDOR_FIRST + 3 class _ManagementCtapBackend(_Backend): def __init__(self, fido_connection): self.ctap = fido_connection version = fido_connection.device_version if version[0] < 4: # Prior to YK4 this was not firmware version if not ( version[0] == 0 and fido_connection.capabilities & CTAP_CAPABILITY.CBOR ): version = (3, 0, 0) # Guess that it's a NEO self.version = Version(*version) def close(self): self.ctap.close() def set_mode(self, data): self.ctap.call(CTAP_YUBIKEY_DEVICE_CONFIG, data) def read_config(self): return self.ctap.call(CTAP_READ_CONFIG) def write_config(self, config): self.ctap.call(CTAP_WRITE_CONFIG, config) class ManagementSession: def __init__( self, connection: Union[OtpConnection, SmartCardConnection, FidoConnection] ): if isinstance(connection, OtpConnection): self.backend: _Backend = _ManagementOtpBackend(connection) elif isinstance(connection, SmartCardConnection): self.backend = _ManagementSmartCardBackend(connection) elif isinstance(connection, FidoConnection): self.backend = _ManagementCtapBackend(connection) else: raise TypeError("Unsupported connection type") logger.debug( "Management session initialized for " f"connection={type(connection).__name__}, version={self.version}" ) def close(self) -> None: self.backend.close() @property def version(self) -> Version: return self.backend.version def read_device_info(self) -> DeviceInfo: """Get detailed information about the YubiKey.""" require_version(self.version, (4, 1, 0)) return DeviceInfo.parse(self.backend.read_config(), self.version) def write_device_config( self, config: Optional[DeviceConfig] = None, reboot: bool = False, cur_lock_code: Optional[bytes] = None, new_lock_code: Optional[bytes] = None, ) -> None: """Write configuration settings for YubiKey. :pararm config: The device configuration. :param reboot: If True the YubiKey will reboot. :param cur_lock_code: Current lock code. :param new_lock_code: New lock code. """ require_version(self.version, (5, 0, 0)) if cur_lock_code is not None and len(cur_lock_code) != 16: raise ValueError("Lock code must be 16 bytes") if new_lock_code is not None and len(new_lock_code) != 16: raise ValueError("Lock code must be 16 bytes") config = config or DeviceConfig({}, None, None, None) logger.debug( f"Writing device config: {config}, reboot: {reboot}, " f"current lock code: {cur_lock_code is not None}, " f"new lock code: {new_lock_code is not None}" ) self.backend.write_config( config.get_bytes(reboot, cur_lock_code, new_lock_code) ) logger.info("Device config written") def set_mode( self, mode: Mode, chalresp_timeout: int = 0, auto_eject_timeout: Optional[int] = None, ) -> None: """Write connection modes (USB interfaces) for YubiKey. :param mode: The connection modes (USB interfaces). :param chalresp_timeout: The timeout when waiting for touch for challenge response. :param auto_eject_timeout: When set, the smartcard will automatically eject after the given time. """ logger.debug( f"Set mode: {mode}, chalresp_timeout: {chalresp_timeout}, " f"auto_eject_timeout: {auto_eject_timeout}" ) if self.version >= (5, 0, 0): # Translate into DeviceConfig usb_enabled = CAPABILITY(0) if USB_INTERFACE.OTP in mode.interfaces: usb_enabled |= CAPABILITY.OTP if USB_INTERFACE.CCID in mode.interfaces: usb_enabled |= CAPABILITY.OATH | CAPABILITY.PIV | CAPABILITY.OPENPGP if USB_INTERFACE.FIDO in mode.interfaces: usb_enabled |= CAPABILITY.U2F | CAPABILITY.FIDO2 logger.debug(f"Delegating to DeviceConfig with usb_enabled: {usb_enabled}") # N.B: reboot=False, since we're using the older set_mode command self.write_device_config( DeviceConfig( {TRANSPORT.USB: usb_enabled}, auto_eject_timeout, chalresp_timeout, None, ) ) else: code = mode.code if auto_eject_timeout is not None: if mode.interfaces == USB_INTERFACE.CCID: code |= DEVICE_FLAG.EJECT else: raise ValueError("Touch-eject only applicable for mode: CCID") self.backend.set_mode( # N.B. This is little endian! struct.pack("<BBH", code, chalresp_timeout, auto_eject_timeout or 0) ) logger.info("Mode configuration written")
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/management.py
management.py
from .core import ( Tlv, Version, NotSupportedError, InvalidPinError, require_version, int2bytes, bytes2int, ) from .core.smartcard import ( SmartCardConnection, SmartCardProtocol, ApduFormat, ApduError, AID, SW, ) from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.serialization import ( Encoding, PrivateFormat, PublicFormat, NoEncryption, ) from cryptography.hazmat.primitives.asymmetric import rsa, ec, ed25519, x25519 from cryptography.hazmat.primitives.asymmetric.utils import ( Prehashed, encode_dss_signature, ) import os import abc from enum import Enum, IntEnum, IntFlag, unique from dataclasses import dataclass from typing import ( Optional, Tuple, ClassVar, Mapping, Sequence, SupportsBytes, Union, Dict, List, ) import struct import logging logger = logging.getLogger(__name__) DEFAULT_USER_PIN = "123456" DEFAULT_ADMIN_PIN = "12345678" @unique class UIF(IntEnum): # noqa: N801 OFF = 0x00 ON = 0x01 FIXED = 0x02 CACHED = 0x03 CACHED_FIXED = 0x04 @classmethod def parse(cls, encoded: bytes): return cls(encoded[0]) def __bytes__(self) -> bytes: return struct.pack(">BB", self, GENERAL_FEATURE_MANAGEMENT.BUTTON) @property def is_fixed(self) -> bool: return self in (UIF.FIXED, UIF.CACHED_FIXED) @property def is_cached(self) -> bool: return self in (UIF.CACHED, UIF.CACHED_FIXED) def __str__(self): if self == UIF.FIXED: return "On (fixed)" if self == UIF.CACHED_FIXED: return "Cached (fixed)" return self.name[0] + self.name[1:].lower() @unique class PIN_POLICY(IntEnum): # noqa: N801 ALWAYS = 0x00 ONCE = 0x01 def __str__(self): return self.name[0] + self.name[1:].lower() @unique class INS(IntEnum): # noqa: N801 VERIFY = 0x20 CHANGE_PIN = 0x24 RESET_RETRY_COUNTER = 0x2C PSO = 0x2A ACTIVATE = 0x44 GENERATE_ASYM = 0x47 GET_CHALLENGE = 0x84 INTERNAL_AUTHENTICATE = 0x88 SELECT_DATA = 0xA5 GET_DATA = 0xCA PUT_DATA = 0xDA PUT_DATA_ODD = 0xDB TERMINATE = 0xE6 GET_VERSION = 0xF1 SET_PIN_RETRIES = 0xF2 GET_ATTESTATION = 0xFB _INVALID_PIN = b"\0" * 8 TAG_DISCRETIONARY = 0x73 TAG_EXTENDED_CAPABILITIES = 0xC0 TAG_FINGERPRINTS = 0xC5 TAG_CA_FINGERPRINTS = 0xC6 TAG_GENERATION_TIMES = 0xCD TAG_SIGNATURE_COUNTER = 0x93 TAG_KEY_INFORMATION = 0xDE TAG_PUBLIC_KEY = 0x7F49 @unique class PW(IntEnum): USER = 0x81 RESET = 0x82 ADMIN = 0x83 @unique class DO(IntEnum): PRIVATE_USE_1 = 0x0101 PRIVATE_USE_2 = 0x0102 PRIVATE_USE_3 = 0x0103 PRIVATE_USE_4 = 0x0104 AID = 0x4F NAME = 0x5B LOGIN_DATA = 0x5E LANGUAGE = 0xEF2D SEX = 0x5F35 URL = 0x5F50 HISTORICAL_BYTES = 0x5F52 EXTENDED_LENGTH_INFO = 0x7F66 GENERAL_FEATURE_MANAGEMENT = 0x7F74 CARDHOLDER_RELATED_DATA = 0x65 APPLICATION_RELATED_DATA = 0x6E ALGORITHM_ATTRIBUTES_SIG = 0xC1 ALGORITHM_ATTRIBUTES_DEC = 0xC2 ALGORITHM_ATTRIBUTES_AUT = 0xC3 ALGORITHM_ATTRIBUTES_ATT = 0xDA PW_STATUS_BYTES = 0xC4 FINGERPRINT_SIG = 0xC7 FINGERPRINT_DEC = 0xC8 FINGERPRINT_AUT = 0xC9 FINGERPRINT_ATT = 0xDB CA_FINGERPRINT_1 = 0xCA CA_FINGERPRINT_2 = 0xCB CA_FINGERPRINT_3 = 0xCC CA_FINGERPRINT_4 = 0xDC GENERATION_TIME_SIG = 0xCE GENERATION_TIME_DEC = 0xCF GENERATION_TIME_AUT = 0xD0 GENERATION_TIME_ATT = 0xDD RESETTING_CODE = 0xD3 UIF_SIG = 0xD6 UIF_DEC = 0xD7 UIF_AUT = 0xD8 UIF_ATT = 0xD9 SECURITY_SUPPORT_TEMPLATE = 0x7A CARDHOLDER_CERTIFICATE = 0x7F21 KDF = 0xF9 ALGORITHM_INFORMATION = 0xFA ATT_CERTIFICATE = 0xFC def _bcd(value: int) -> int: return 10 * (value >> 4) + (value & 0xF) class OpenPgpAid(bytes): """OpenPGP Application Identifier (AID) The OpenPGP AID is a string of bytes identifying the OpenPGP application. It also embeds some values which are accessible though properties. """ @property def version(self) -> Tuple[int, int]: """OpenPGP version (tuple of 2 integers: main version, secondary version).""" return (_bcd(self[6]), _bcd(self[7])) @property def manufacturer(self) -> int: """16-bit integer value identifying the manufacturer of the device. This should be 6 for Yubico devices. """ return bytes2int(self[8:10]) @property def serial(self) -> int: """The serial number of the YubiKey. NOTE: This value is encoded in BCD. In the event of an invalid value (hex A-F) the entire 4 byte value will instead be decoded as an unsigned integer, and negated. """ try: return int(self[10:14].hex()) except ValueError: # Not valid BCD, treat as an unsigned integer, and return a negative value return -struct.unpack(">I", self[10:14])[0] @unique class EXTENDED_CAPABILITY_FLAGS(IntFlag): KDF = 1 << 0 PSO_DEC_ENC_AES = 1 << 1 ALGORITHM_ATTRIBUTES_CHANGEABLE = 1 << 2 PRIVATE_USE = 1 << 3 PW_STATUS_CHANGEABLE = 1 << 4 KEY_IMPORT = 1 << 5 GET_CHALLENGE = 1 << 6 SECURE_MESSAGING = 1 << 7 @dataclass class CardholderRelatedData: name: bytes language: bytes sex: int @classmethod def parse(cls, encoded) -> "CardholderRelatedData": data = Tlv.parse_dict(Tlv.unpack(DO.CARDHOLDER_RELATED_DATA, encoded)) return cls( data[DO.NAME], data[DO.LANGUAGE], data[DO.SEX][0], ) @dataclass class ExtendedLengthInfo: request_max_bytes: int response_max_bytes: int @classmethod def parse(cls, encoded) -> "ExtendedLengthInfo": data = Tlv.parse_list(encoded) return cls( bytes2int(Tlv.unpack(0x02, data[0])), bytes2int(Tlv.unpack(0x02, data[1])), ) @unique class GENERAL_FEATURE_MANAGEMENT(IntFlag): TOUCHSCREEN = 1 << 0 MICROPHONE = 1 << 1 LOUDSPEAKER = 1 << 2 LED = 1 << 3 KEYPAD = 1 << 4 BUTTON = 1 << 5 BIOMETRIC = 1 << 6 DISPLAY = 1 << 7 @dataclass class ExtendedCapabilities: flags: EXTENDED_CAPABILITY_FLAGS sm_algorithm: int challenge_max_length: int certificate_max_length: int special_do_max_length: int pin_block_2_format: bool mse_command: bool @classmethod def parse(cls, encoded: bytes) -> "ExtendedCapabilities": return cls( EXTENDED_CAPABILITY_FLAGS(encoded[0]), encoded[1], bytes2int(encoded[2:4]), bytes2int(encoded[4:6]), bytes2int(encoded[6:8]), encoded[8] == 1, encoded[9] == 1, ) @dataclass class PwStatus: pin_policy_user: PIN_POLICY max_len_user: int max_len_reset: int max_len_admin: int attempts_user: int attempts_reset: int attempts_admin: int def get_max_len(self, pw: PW) -> int: return getattr(self, f"max_len_{pw.name.lower()}") def get_attempts(self, pw: PW) -> int: return getattr(self, f"attempts_{pw.name.lower()}") @classmethod def parse(cls, encoded: bytes) -> "PwStatus": try: policy = PIN_POLICY(encoded[0]) except ValueError: policy = PIN_POLICY.ONCE return cls( policy, encoded[1], encoded[2], encoded[3], encoded[4], encoded[5], encoded[6], ) @unique class CRT(bytes, Enum): """Control Reference Template values.""" SIG = Tlv(0xB6) DEC = Tlv(0xB8) AUT = Tlv(0xA4) ATT = Tlv(0xB6, Tlv(0x84, b"\x81")) @unique class KEY_REF(IntEnum): # noqa: N801 SIG = 0x01 DEC = 0x02 AUT = 0x03 ATT = 0x81 @property def algorithm_attributes_do(self) -> DO: return getattr(DO, f"ALGORITHM_ATTRIBUTES_{self.name}") @property def uif_do(self) -> DO: return getattr(DO, f"UIF_{self.name}") @property def generation_time_do(self) -> DO: return getattr(DO, f"GENERATION_TIME_{self.name}") @property def fingerprint_do(self) -> DO: return getattr(DO, f"FINGERPRINT_{self.name}") @property def crt(self) -> CRT: return getattr(CRT, self.name) @unique class KEY_STATUS(IntEnum): NONE = 0 GENERATED = 1 IMPORTED = 2 KeyInformation = Mapping[KEY_REF, KEY_STATUS] Fingerprints = Mapping[KEY_REF, bytes] GenerationTimes = Mapping[KEY_REF, int] EcPublicKey = Union[ ec.EllipticCurvePublicKey, ed25519.Ed25519PublicKey, x25519.X25519PublicKey, ] PublicKey = Union[EcPublicKey, rsa.RSAPublicKey] EcPrivateKey = Union[ ec.EllipticCurvePrivateKeyWithSerialization, ed25519.Ed25519PrivateKey, x25519.X25519PrivateKey, ] PrivateKey = Union[ rsa.RSAPrivateKeyWithSerialization, EcPrivateKey, ] # mypy doesn't handle abstract dataclasses well @dataclass # type: ignore[misc] class AlgorithmAttributes(abc.ABC): """OpenPGP key algorithm attributes.""" _supported_ids: ClassVar[Sequence[int]] algorithm_id: int @classmethod def parse(cls, encoded: bytes) -> "AlgorithmAttributes": algorithm_id = encoded[0] for sub_cls in cls.__subclasses__(): if algorithm_id in sub_cls._supported_ids: return sub_cls._parse_data(algorithm_id, encoded[1:]) raise ValueError("Unsupported algorithm ID") @abc.abstractmethod def __bytes__(self) -> bytes: raise NotImplementedError() @classmethod @abc.abstractmethod def _parse_data(cls, alg: int, encoded: bytes) -> "AlgorithmAttributes": raise NotImplementedError() @unique class RSA_SIZE(IntEnum): RSA2048 = 2048 RSA3072 = 3072 RSA4096 = 4096 @unique class RSA_IMPORT_FORMAT(IntEnum): STANDARD = 0 STANDARD_W_MOD = 1 CRT = 2 CRT_W_MOD = 3 @dataclass class RsaAttributes(AlgorithmAttributes): _supported_ids = [0x01] n_len: int e_len: int import_format: RSA_IMPORT_FORMAT @classmethod def create( cls, n_len: RSA_SIZE, import_format: RSA_IMPORT_FORMAT = RSA_IMPORT_FORMAT.STANDARD, ) -> "RsaAttributes": return cls(0x01, n_len, 17, import_format) @classmethod def _parse_data(cls, alg, encoded) -> "RsaAttributes": n, e, f = struct.unpack(">HHB", encoded) return cls(alg, n, e, RSA_IMPORT_FORMAT(f)) def __bytes__(self) -> bytes: return struct.pack( ">BHHB", self.algorithm_id, self.n_len, self.e_len, self.import_format ) class CurveOid(bytes): def _get_name(self) -> str: for oid in OID: if self.startswith(oid): return oid.name return "Unknown Curve" def __str__(self) -> str: return self._get_name() def __repr__(self) -> str: name = self._get_name() return f"{name}({self.hex()})" class OID(CurveOid, Enum): SECP256R1 = CurveOid(b"\x2a\x86\x48\xce\x3d\x03\x01\x07") SECP256K1 = CurveOid(b"\x2b\x81\x04\x00\x0a") SECP384R1 = CurveOid(b"\x2b\x81\x04\x00\x22") SECP521R1 = CurveOid(b"\x2b\x81\x04\x00\x23") BrainpoolP256R1 = CurveOid(b"\x2b\x24\x03\x03\x02\x08\x01\x01\x07") BrainpoolP384R1 = CurveOid(b"\x2b\x24\x03\x03\x02\x08\x01\x01\x0b") BrainpoolP512R1 = CurveOid(b"\x2b\x24\x03\x03\x02\x08\x01\x01\x0d") X25519 = CurveOid(b"\x2b\x06\x01\x04\x01\x97\x55\x01\x05\x01") Ed25519 = CurveOid(b"\x2b\x06\x01\x04\x01\xda\x47\x0f\x01") @classmethod def _from_key(cls, private_key: EcPrivateKey) -> CurveOid: name = "" if isinstance(private_key, ec.EllipticCurvePrivateKey): name = private_key.curve.name.lower() else: if isinstance(private_key, ed25519.Ed25519PrivateKey): name = "ed25519" elif isinstance(private_key, x25519.X25519PrivateKey): name = "x25519" for oid in cls: if oid.name.lower() == name: return oid raise ValueError("Unsupported private key") def __repr__(self) -> str: return repr(self.value) def __str__(self) -> str: return str(self.value) @unique class EC_IMPORT_FORMAT(IntEnum): STANDARD = 0 STANDARD_W_PUBKEY = 0xFF @dataclass class EcAttributes(AlgorithmAttributes): _supported_ids = [0x12, 0x13, 0x16] oid: CurveOid import_format: EC_IMPORT_FORMAT @classmethod def create(cls, key_ref: KEY_REF, oid: CurveOid) -> "EcAttributes": if oid == OID.Ed25519: alg = 0x16 # EdDSA elif key_ref == KEY_REF.DEC: alg = 0x12 # ECDH else: alg = 0x13 # ECDSA return cls(alg, oid, EC_IMPORT_FORMAT.STANDARD) @classmethod def _parse_data(cls, alg, encoded) -> "EcAttributes": if encoded[-1] == 0xFF: f = EC_IMPORT_FORMAT.STANDARD_W_PUBKEY oid = encoded[:-1] else: # Standard is defined as "format byte not present" f = EC_IMPORT_FORMAT.STANDARD oid = encoded return cls(alg, CurveOid(oid), f) def __bytes__(self) -> bytes: buf = struct.pack(">B", self.algorithm_id) + self.oid if self.import_format == EC_IMPORT_FORMAT.STANDARD_W_PUBKEY: buf += struct.pack(">B", self.import_format) return buf def _parse_key_information(encoded: bytes) -> KeyInformation: return { KEY_REF(encoded[i]): KEY_STATUS(encoded[i + 1]) for i in range(0, len(encoded), 2) } def _parse_fingerprints(encoded: bytes) -> Fingerprints: slots = list(KEY_REF) return { slots[i]: encoded[o : o + 20] for i, o in enumerate(range(0, len(encoded), 20)) } def _parse_timestamps(encoded: bytes) -> GenerationTimes: slots = list(KEY_REF) return { slots[i]: bytes2int(encoded[o : o + 4]) for i, o in enumerate(range(0, len(encoded), 4)) } @dataclass class DiscretionaryDataObjects: extended_capabilities: ExtendedCapabilities attributes_sig: AlgorithmAttributes attributes_dec: AlgorithmAttributes attributes_aut: AlgorithmAttributes attributes_att: Optional[AlgorithmAttributes] pw_status: PwStatus fingerprints: Fingerprints ca_fingerprints: Fingerprints generation_times: GenerationTimes key_information: KeyInformation uif_sig: Optional[UIF] uif_dec: Optional[UIF] uif_aut: Optional[UIF] uif_att: Optional[UIF] @classmethod def parse(cls, encoded: bytes) -> "DiscretionaryDataObjects": data = Tlv.parse_dict(encoded) return cls( ExtendedCapabilities.parse(data[TAG_EXTENDED_CAPABILITIES]), AlgorithmAttributes.parse(data[DO.ALGORITHM_ATTRIBUTES_SIG]), AlgorithmAttributes.parse(data[DO.ALGORITHM_ATTRIBUTES_DEC]), AlgorithmAttributes.parse(data[DO.ALGORITHM_ATTRIBUTES_AUT]), ( AlgorithmAttributes.parse(data[DO.ALGORITHM_ATTRIBUTES_ATT]) if DO.ALGORITHM_ATTRIBUTES_ATT in data else None ), PwStatus.parse(data[DO.PW_STATUS_BYTES]), _parse_fingerprints(data[TAG_FINGERPRINTS]), _parse_fingerprints(data[TAG_CA_FINGERPRINTS]), _parse_timestamps(data[TAG_GENERATION_TIMES]), _parse_key_information(data.get(TAG_KEY_INFORMATION, b"")), (UIF.parse(data[DO.UIF_SIG]) if DO.UIF_SIG in data else None), (UIF.parse(data[DO.UIF_DEC]) if DO.UIF_DEC in data else None), (UIF.parse(data[DO.UIF_AUT]) if DO.UIF_AUT in data else None), (UIF.parse(data[DO.UIF_ATT]) if DO.UIF_ATT in data else None), ) def get_algorithm_attributes(self, key_ref: KEY_REF) -> AlgorithmAttributes: return getattr(self, f"attributes_{key_ref.name.lower()}") @dataclass class ApplicationRelatedData: """OpenPGP related data.""" aid: OpenPgpAid historical: bytes extended_length_info: Optional[ExtendedLengthInfo] general_feature_management: Optional[GENERAL_FEATURE_MANAGEMENT] discretionary: DiscretionaryDataObjects @classmethod def parse(cls, encoded: bytes) -> "ApplicationRelatedData": outer = Tlv.unpack(DO.APPLICATION_RELATED_DATA, encoded) data = Tlv.parse_dict(outer) return cls( OpenPgpAid(data[DO.AID]), data[DO.HISTORICAL_BYTES], ( ExtendedLengthInfo.parse(data[DO.EXTENDED_LENGTH_INFO]) if DO.EXTENDED_LENGTH_INFO in data else None ), ( GENERAL_FEATURE_MANAGEMENT( Tlv.unpack(0x81, data[DO.GENERAL_FEATURE_MANAGEMENT])[0] ) if DO.GENERAL_FEATURE_MANAGEMENT in data else None ), # Older keys have data in outer dict DiscretionaryDataObjects.parse(data[TAG_DISCRETIONARY] or outer), ) @dataclass class SecuritySupportTemplate: signature_counter: int @classmethod def parse(cls, encoded: bytes) -> "SecuritySupportTemplate": data = Tlv.parse_dict(Tlv.unpack(DO.SECURITY_SUPPORT_TEMPLATE, encoded)) return cls(bytes2int(data[TAG_SIGNATURE_COUNTER])) # mypy doesn't handle abstract dataclasses well @dataclass # type: ignore[misc] class Kdf(abc.ABC): algorithm: ClassVar[int] @abc.abstractmethod def process(self, pin: str, pw: PW) -> bytes: """Run the KDF on the input PIN.""" @classmethod @abc.abstractmethod def _parse_data(cls, data: Mapping[int, bytes]) -> "Kdf": raise NotImplementedError() @classmethod def parse(cls, encoded: bytes) -> "Kdf": data = Tlv.parse_dict(encoded) try: algorithm = bytes2int(data[0x81]) for sub in cls.__subclasses__(): if sub.algorithm == algorithm: return sub._parse_data(data) except KeyError: pass # Fall though to KdfNone return KdfNone() @abc.abstractmethod def __bytes__(self) -> bytes: raise NotImplementedError() @dataclass class KdfNone(Kdf): algorithm = 0 @classmethod def _parse_data(cls, data) -> "KdfNone": return cls() def process(self, pw, pin): return pin.encode() def __bytes__(self): return Tlv(0x81, struct.pack(">B", self.algorithm)) @unique class HASH_ALGORITHM(IntEnum): SHA256 = 0x08 SHA512 = 0x0A def create_digest(self): algorithm = getattr(hashes, self.name) return hashes.Hash(algorithm(), default_backend()) @dataclass class KdfIterSaltedS2k(Kdf): algorithm = 3 hash_algorithm: HASH_ALGORITHM iteration_count: int salt_user: bytes salt_reset: bytes salt_admin: bytes initial_hash_user: Optional[bytes] initial_hash_admin: Optional[bytes] @staticmethod def _do_process(hash_algorithm, iteration_count, data): # Although the field is called "iteration count", it's actually # the number of bytes to be passed to the hash function, which # is called only once. Go figure! data_count, trailing_bytes = divmod(iteration_count, len(data)) digest = hash_algorithm.create_digest() for _ in range(data_count): digest.update(data) digest.update(data[:trailing_bytes]) return digest.finalize() @classmethod def create( cls, hash_algorithm: HASH_ALGORITHM = HASH_ALGORITHM.SHA256, iteration_count: int = 0x780000, ) -> "KdfIterSaltedS2k": salt_user = os.urandom(8) salt_admin = os.urandom(8) return cls( hash_algorithm, iteration_count, salt_user, os.urandom(8), salt_admin, cls._do_process( hash_algorithm, iteration_count, salt_user + DEFAULT_USER_PIN.encode() ), cls._do_process( hash_algorithm, iteration_count, salt_admin + DEFAULT_ADMIN_PIN.encode() ), ) @classmethod def _parse_data(cls, data) -> "KdfIterSaltedS2k": return cls( HASH_ALGORITHM(bytes2int(data[0x82])), bytes2int(data[0x83]), data[0x84], data.get(0x85), data.get(0x86), data.get(0x87), data.get(0x88), ) def get_salt(self, pw: PW) -> bytes: return getattr(self, f"salt_{pw.name.lower()}") def process(self, pw, pin): salt = self.get_salt(pw) or self.salt_user data = salt + pin.encode() return self._do_process(self.hash_algorithm, self.iteration_count, data) def __bytes__(self): return ( Tlv(0x81, struct.pack(">B", self.algorithm)) + Tlv(0x82, struct.pack(">B", self.hash_algorithm)) + Tlv(0x83, struct.pack(">I", self.iteration_count)) + Tlv(0x84, self.salt_user) + (Tlv(0x85, self.salt_reset) if self.salt_reset else b"") + (Tlv(0x86, self.salt_admin) if self.salt_admin else b"") + (Tlv(0x87, self.initial_hash_user) if self.initial_hash_user else b"") + (Tlv(0x88, self.initial_hash_admin) if self.initial_hash_admin else b"") ) # mypy doesn't handle abstract dataclasses well @dataclass # type: ignore[misc] class PrivateKeyTemplate(abc.ABC): crt: CRT def _get_template(self) -> Sequence[Tlv]: raise NotImplementedError() def __bytes__(self) -> bytes: tlvs = self._get_template() return Tlv( 0x4D, self.crt + Tlv(0x7F48, b"".join(tlv[: -tlv.length] for tlv in tlvs)) + Tlv(0x5F48, b"".join(tlv.value for tlv in tlvs)), ) @dataclass class RsaKeyTemplate(PrivateKeyTemplate): e: bytes p: bytes q: bytes def _get_template(self): return ( Tlv(0x91, self.e), Tlv(0x92, self.p), Tlv(0x93, self.q), ) @dataclass class RsaCrtKeyTemplate(RsaKeyTemplate): iqmp: bytes dmp1: bytes dmq1: bytes n: bytes def _get_template(self): return ( *super()._get_template(), Tlv(0x94, self.iqmp), Tlv(0x95, self.dmp1), Tlv(0x96, self.dmq1), Tlv(0x97, self.n), ) @dataclass class EcKeyTemplate(PrivateKeyTemplate): private_key: bytes public_key: Optional[bytes] def _get_template(self): tlvs: Tuple[Tlv, ...] = (Tlv(0x92, self.private_key),) if self.public_key: tlvs = (*tlvs, Tlv(0x99, self.public_key)) return tlvs def _get_key_attributes( private_key: PrivateKey, key_ref: KEY_REF, version: Version ) -> AlgorithmAttributes: if isinstance(private_key, rsa.RSAPrivateKeyWithSerialization): if private_key.private_numbers().public_numbers.e != 65537: raise ValueError("RSA keys with e != 65537 are not supported!") return RsaAttributes.create( RSA_SIZE(private_key.key_size), RSA_IMPORT_FORMAT.CRT_W_MOD if version < (4, 0, 0) else RSA_IMPORT_FORMAT.STANDARD, ) return EcAttributes.create(key_ref, OID._from_key(private_key)) def _get_key_template( private_key: PrivateKey, key_ref: KEY_REF, use_crt: bool = False ) -> PrivateKeyTemplate: if isinstance(private_key, rsa.RSAPrivateKeyWithSerialization): rsa_numbers = private_key.private_numbers() ln = (private_key.key_size // 8) // 2 e = b"\x01\x00\x01" # e=65537 p = int2bytes(rsa_numbers.p, ln) q = int2bytes(rsa_numbers.q, ln) if not use_crt: return RsaKeyTemplate(key_ref.crt, e, p, q) else: dp = int2bytes(rsa_numbers.dmp1, ln) dq = int2bytes(rsa_numbers.dmq1, ln) qinv = int2bytes(rsa_numbers.iqmp, ln) n = int2bytes(rsa_numbers.public_numbers.n, 2 * ln) return RsaCrtKeyTemplate(key_ref.crt, e, p, q, qinv, dp, dq, n) elif isinstance(private_key, ec.EllipticCurvePrivateKeyWithSerialization): ec_numbers = private_key.private_numbers() ln = private_key.key_size // 8 return EcKeyTemplate(key_ref.crt, int2bytes(ec_numbers.private_value, ln), None) elif isinstance(private_key, (ed25519.Ed25519PrivateKey, x25519.X25519PrivateKey)): pkb = private_key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()) if isinstance(private_key, x25519.X25519PrivateKey): pkb = pkb[::-1] # byte order needs to be reversed return EcKeyTemplate( key_ref.crt, pkb, None, ) raise ValueError("Unsupported key type") def _parse_rsa_key(data: Mapping[int, bytes]) -> rsa.RSAPublicKey: numbers = rsa.RSAPublicNumbers(bytes2int(data[0x82]), bytes2int(data[0x81])) return numbers.public_key(default_backend()) def _parse_ec_key(oid: CurveOid, data: Mapping[int, bytes]) -> EcPublicKey: pubkey_enc = data[0x86] if oid == OID.X25519: return x25519.X25519PublicKey.from_public_bytes(pubkey_enc) if oid == OID.Ed25519: return ed25519.Ed25519PublicKey.from_public_bytes(pubkey_enc) curve = getattr(ec, oid._get_name()) return ec.EllipticCurvePublicKey.from_encoded_point(curve(), pubkey_enc) _pkcs1v15_headers = { hashes.MD5: bytes.fromhex("3020300C06082A864886F70D020505000410"), hashes.SHA1: bytes.fromhex("3021300906052B0E03021A05000414"), hashes.SHA224: bytes.fromhex("302D300D06096086480165030402040500041C"), hashes.SHA256: bytes.fromhex("3031300D060960864801650304020105000420"), hashes.SHA384: bytes.fromhex("3041300D060960864801650304020205000430"), hashes.SHA512: bytes.fromhex("3051300D060960864801650304020305000440"), hashes.SHA512_224: bytes.fromhex("302D300D06096086480165030402050500041C"), hashes.SHA512_256: bytes.fromhex("3031300D060960864801650304020605000420"), } def _pad_message(attributes, message, hash_algorithm): if attributes.algorithm_id == 0x16: # EdDSA, never hash return message if isinstance(hash_algorithm, Prehashed): hashed = message else: h = hashes.Hash(hash_algorithm, default_backend()) h.update(message) hashed = h.finalize() if isinstance(attributes, EcAttributes): return hashed if isinstance(attributes, RsaAttributes): try: return _pkcs1v15_headers[type(hash_algorithm)] + hashed except KeyError: raise ValueError(f"Unsupported hash algorithm for RSA: {hash_algorithm}") class OpenPgpSession: """A session with the OpenPGP application.""" def __init__(self, connection: SmartCardConnection): self.protocol = SmartCardProtocol(connection) try: self.protocol.select(AID.OPENPGP) except ApduError as e: if e.sw in (SW.NO_INPUT_DATA, SW.CONDITIONS_NOT_SATISFIED): # Not activated, activate logger.warning("Application not active, sending ACTIVATE") self.protocol.send_apdu(0, INS.ACTIVATE, 0, 0) self.protocol.select(AID.OPENPGP) else: raise self._version = self._read_version() self.protocol.enable_touch_workaround(self.version) if self.version >= (4, 0, 0): self.protocol.apdu_format = ApduFormat.EXTENDED # Note: This value is cached! # Do not rely on contained information that can change! self._app_data = self.get_application_related_data() logger.debug(f"OpenPGP session initialized (version={self.version})") def _read_version(self) -> Version: logger.debug("Getting version number") bcd = self.protocol.send_apdu(0, INS.GET_VERSION, 0, 0) return Version(*(_bcd(x) for x in bcd)) @property def aid(self) -> OpenPgpAid: """Get the AID used to select the applet.""" return self._app_data.aid @property def version(self) -> Version: """Get the firmware version of the key. For YubiKey NEO this is the PGP applet version. """ return self._version @property def extended_capabilities(self) -> ExtendedCapabilities: """Get the Extended Capabilities from the YubiKey.""" return self._app_data.discretionary.extended_capabilities def get_challenge(self, length: int) -> bytes: """Get random data from the YubiKey. :param length: Length of the returned data. """ e = self.extended_capabilities if EXTENDED_CAPABILITY_FLAGS.GET_CHALLENGE not in e.flags: raise NotSupportedError("GET_CHALLENGE is not supported") if not 0 < length <= e.challenge_max_length: raise NotSupportedError("Unsupported challenge length") logger.debug(f"Getting {length} random bytes") return self.protocol.send_apdu(0, INS.GET_CHALLENGE, 0, 0, le=length) def get_data(self, do: DO) -> bytes: """Get a Data Object from the YubiKey. :param do: The Data Object to get. """ logger.debug(f"Reading Data Object {do.name} ({do:X})") return self.protocol.send_apdu(0, INS.GET_DATA, do >> 8, do & 0xFF) def put_data(self, do: DO, data: Union[bytes, SupportsBytes]) -> None: """Write a Data Object to the YubiKey. :param do: The Data Object to write to. :param data: The data to write. """ self.protocol.send_apdu(0, INS.PUT_DATA, do >> 8, do & 0xFF, bytes(data)) logger.info(f"Wrote Data Object {do.name} ({do:X})") def get_pin_status(self) -> PwStatus: """Get the current status of PINS.""" return PwStatus.parse(self.get_data(DO.PW_STATUS_BYTES)) def get_signature_counter(self) -> int: """Get the number of times the signature key has been used.""" s = SecuritySupportTemplate.parse(self.get_data(DO.SECURITY_SUPPORT_TEMPLATE)) return s.signature_counter def get_application_related_data(self) -> ApplicationRelatedData: """Read the Application Related Data.""" return ApplicationRelatedData.parse(self.get_data(DO.APPLICATION_RELATED_DATA)) def set_signature_pin_policy(self, pin_policy: PIN_POLICY) -> None: """Set signature PIN policy. Requires Admin PIN verification. :param pin_policy: The PIN policy. """ logger.debug(f"Setting Signature PIN policy to {pin_policy}") data = struct.pack(">B", pin_policy) self.put_data(DO.PW_STATUS_BYTES, data) logger.info("Signature PIN policy set") def reset(self) -> None: """Perform a factory reset on the OpenPGP application. WARNING: This will delete all stored keys, certificates and other data. """ require_version(self.version, (1, 0, 6)) logger.debug("Preparing OpenPGP reset") # Ensure the User and Admin PINs are blocked status = self.get_pin_status() for pw in (PW.USER, PW.ADMIN): logger.debug(f"Verify {pw.name} PIN with invalid attempts until blocked") for _ in range(status.get_attempts(pw)): try: self.protocol.send_apdu(0, INS.VERIFY, 0, pw, _INVALID_PIN) except ApduError: pass # Reset the application logger.debug("Sending TERMINATE, then ACTIVATE") self.protocol.send_apdu(0, INS.TERMINATE, 0, 0) self.protocol.send_apdu(0, INS.ACTIVATE, 0, 0) logger.info("OpenPGP application data reset performed") def set_pin_attempts( self, user_attempts: int, reset_attempts: int, admin_attempts: int ) -> None: """Set the number of PIN attempts to allow before blocking. WARNING: On YubiKey NEO this will reset the PINs to their default values. Requires Admin PIN verification. :param user_attempts: The User PIN attempts. :param reset_attempts: The Reset Code attempts. :param admin_attempts: The Admin PIN attempts. """ if self.version[0] == 1: # YubiKey NEO require_version(self.version, (1, 0, 7)) else: require_version(self.version, (4, 3, 1)) attempts = (user_attempts, reset_attempts, admin_attempts) logger.debug(f"Setting PIN attempts to {attempts}") self.protocol.send_apdu( 0, INS.SET_PIN_RETRIES, 0, 0, struct.pack(">BBB", *attempts), ) logger.info("Number of PIN attempts has been changed") def get_kdf(self): """Get the Key Derivation Function data object.""" if EXTENDED_CAPABILITY_FLAGS.KDF not in self.extended_capabilities.flags: return KdfNone() return Kdf.parse(self.get_data(DO.KDF)) def set_kdf(self, kdf: Kdf) -> None: """Set up a PIN Key Derivation Function. This enables (or disables) the use of a KDF for PIN verification, as well as resetting the User and Admin PINs to their default (initial) values. If a Reset Code is present, it will be invalidated. This command requires Admin PIN verification. :param kdf: The key derivation function. """ e = self._app_data.discretionary.extended_capabilities if EXTENDED_CAPABILITY_FLAGS.KDF not in e.flags: raise NotSupportedError("KDF is not supported") logger.debug(f"Setting PIN KDF to algorithm: {kdf.algorithm}") self.put_data(DO.KDF, kdf) logger.info("KDF settings changed") def _verify(self, pw: PW, pin: str, mode: int = 0) -> None: pin_enc = self.get_kdf().process(pw, pin) try: self.protocol.send_apdu(0, INS.VERIFY, 0, pw + mode, pin_enc) except ApduError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: attempts = self.get_pin_status().get_attempts(pw) raise InvalidPinError(attempts) raise e def verify_pin(self, pin, extended: bool = False): """Verify the User PIN. This will unlock functionality that requires User PIN verification. Note that with `extended=False` (default) only sign operations are allowed. Inversely, with `extended=True` sign operations are NOT allowed. :param pin: The User PIN. :param extended: If `False` only sign operations are allowed, otherwise sign operations are NOT allowed. """ logger.debug(f"Verifying User PIN in mode {'82' if extended else '81'}") self._verify(PW.USER, pin, 1 if extended else 0) def verify_admin(self, admin_pin): """Verify the Admin PIN. This will unlock functionality that requires Admin PIN verification. :param admin_pin: The Admin PIN. """ logger.debug("Verifying Admin PIN") self._verify(PW.ADMIN, admin_pin) def unverify_pin(self, pw: PW) -> None: """Reset verification for PIN. :param pw: The User, Admin or Reset PIN """ require_version(self.version, (5, 6, 0)) logger.debug(f"Resetting verification for {pw.name} PIN") self.protocol.send_apdu(0, INS.VERIFY, 0xFF, pw) def _change(self, pw: PW, pin: str, new_pin: str) -> None: logger.debug(f"Changing {pw.name} PIN") kdf = self.get_kdf() try: self.protocol.send_apdu( 0, INS.CHANGE_PIN, 0, pw, kdf.process(pw, pin) + kdf.process(pw, new_pin), ) except ApduError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: attempts = self.get_pin_status().get_attempts(pw) raise InvalidPinError(attempts) raise e logger.info(f"New {pw.name} PIN set") def change_pin(self, pin: str, new_pin: str) -> None: """Change the User PIN. :param pin: The current User PIN. :param new_pin: The new User PIN. """ self._change(PW.USER, pin, new_pin) def change_admin(self, admin_pin: str, new_admin_pin: str) -> None: """Change the Admin PIN. :param admin_pin: The current Admin PIN. :param new_admin_pin: The new Admin PIN. """ self._change(PW.ADMIN, admin_pin, new_admin_pin) def set_reset_code(self, reset_code: str) -> None: """Set the Reset Code for User PIN. The Reset Code can be used to set a new User PIN if it is lost or becomes blocked, using the reset_pin method. This command requires Admin PIN verification. :param reset_code: The Reset Code for User PIN. """ logger.debug("Setting a new PIN Reset Code") data = self.get_kdf().process(PW.RESET, reset_code) self.put_data(DO.RESETTING_CODE, data) logger.info("New Reset Code has been set") def reset_pin(self, new_pin: str, reset_code: Optional[str] = None) -> None: """Reset the User PIN to a new value. This command requires Admin PIN verification, or the Reset Code. :param new_pin: The new user PIN. :param reset_code: The Reset Code. """ logger.debug("Resetting User PIN") p1 = 2 kdf = self.get_kdf() data = kdf.process(PW.USER, new_pin) if reset_code: logger.debug("Using Reset Code") data = kdf.process(PW.RESET, reset_code) + data p1 = 0 try: self.protocol.send_apdu(0, INS.RESET_RETRY_COUNTER, p1, PW.USER, data) except ApduError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED and not reset_code: attempts = self.get_pin_status().attempts_reset raise InvalidPinError( attempts, f"Invalid Reset Code, {attempts} remaining" ) raise e logger.info("New User PIN has been set") def get_algorithm_attributes(self, key_ref: KEY_REF) -> AlgorithmAttributes: """Get the algorithm attributes for one of the key slots. :param key_ref: The key slot. """ logger.debug(f"Getting Algorithm Attributes for {key_ref.name}") data = self.get_application_related_data() return data.discretionary.get_algorithm_attributes(key_ref) def get_algorithm_information( self, ) -> Mapping[KEY_REF, Sequence[AlgorithmAttributes]]: """Get the list of supported algorithm attributes for each key. The return value is a mapping of KEY_REF to a list of supported algorithm attributes, which can be set using set_algorithm_attributes. """ if ( EXTENDED_CAPABILITY_FLAGS.ALGORITHM_ATTRIBUTES_CHANGEABLE not in self.extended_capabilities.flags ): raise NotSupportedError("Writing Algorithm Attributes is not supported") if self.version < (5, 2, 0): sizes = [RSA_SIZE.RSA2048] if self.version < (4, 0, 0): # Neo needs CRT fmt = RSA_IMPORT_FORMAT.CRT_W_MOD else: fmt = RSA_IMPORT_FORMAT.STANDARD if self.version[:2] != (4, 4): # Non-FIPS sizes.extend([RSA_SIZE.RSA3072, RSA_SIZE.RSA4096]) return { KEY_REF.SIG: [RsaAttributes.create(size, fmt) for size in sizes], KEY_REF.DEC: [RsaAttributes.create(size, fmt) for size in sizes], KEY_REF.AUT: [RsaAttributes.create(size, fmt) for size in sizes], } logger.debug("Getting supported Algorithm Information") buf = self.get_data(DO.ALGORITHM_INFORMATION) try: buf = Tlv.unpack(DO.ALGORITHM_INFORMATION, buf) except ValueError: buf = Tlv.unpack(DO.ALGORITHM_INFORMATION, buf + b"\0\0")[:-2] slots = {slot.algorithm_attributes_do: slot for slot in KEY_REF} data: Dict[KEY_REF, List[AlgorithmAttributes]] = {} for tlv in Tlv.parse_list(buf): data.setdefault(slots[DO(tlv.tag)], []).append( AlgorithmAttributes.parse(tlv.value) ) if self.version < (5, 6, 1): # Fix for invalid Curve25519 entries: # Remove X25519 with EdDSA from all keys invalid_x25519 = EcAttributes(0x16, OID.X25519, EC_IMPORT_FORMAT.STANDARD) for values in data.values(): values.remove(invalid_x25519) x25519 = EcAttributes(0x12, OID.X25519, EC_IMPORT_FORMAT.STANDARD) # Add X25519 ECDH for DEC if x25519 not in data[KEY_REF.DEC]: data[KEY_REF.DEC].append(x25519) # Remove EdDSA from DEC, ATT ed25519_attr = EcAttributes(0x16, OID.Ed25519, EC_IMPORT_FORMAT.STANDARD) data[KEY_REF.DEC].remove(ed25519_attr) data[KEY_REF.ATT].remove(ed25519_attr) return data def set_algorithm_attributes( self, key_ref: KEY_REF, attributes: AlgorithmAttributes ) -> None: """Set the algorithm attributes for a key slot. WARNING: This will delete any key already stored in the slot if the attributes are changed! This command requires Admin PIN verification. :param key_ref: The key slot. :param attributes: The algorithm attributes to set. """ logger.debug("Setting Algorithm Attributes for {key_ref.name}") supported = self.get_algorithm_information() if key_ref not in supported: raise NotSupportedError("Key slot not supported") if attributes not in supported[key_ref]: raise NotSupportedError("Algorithm attributes not supported") self.put_data(key_ref.algorithm_attributes_do, attributes) logger.info("Algorithm Attributes have been changed") def get_uif(self, key_ref: KEY_REF) -> UIF: """Get the User Interaction Flag (touch requirement) for a key. :param key_ref: The key slot. """ try: return UIF.parse(self.get_data(key_ref.uif_do)) except ApduError as e: if e.sw == SW.WRONG_PARAMETERS_P1P2: # Not supported return UIF.OFF raise def set_uif(self, key_ref: KEY_REF, uif: UIF) -> None: """Set the User Interaction Flag (touch requirement) for a key. Requires Admin PIN verification. :param key_ref: The key slot. :param uif: The User Interaction Flag. """ require_version(self.version, (4, 2, 0)) if key_ref == KEY_REF.ATT: require_version( self.version, (5, 2, 1), "Attestation key requires YubiKey 5.2.1 or later.", ) if uif.is_cached: require_version( self.version, (5, 2, 1), "Cached UIF values require YubiKey 5.2.1 or later.", ) logger.debug(f"Setting UIF for {key_ref.name} to {uif.name}") if self.get_uif(key_ref).is_fixed: raise ValueError("Cannot change UIF when set to FIXED.") self.put_data(key_ref.uif_do, uif) logger.info(f"UIF changed for {key_ref.name}") def get_key_information(self) -> KeyInformation: """Get the status of the keys.""" logger.debug("Getting Key Information") return self.get_application_related_data().discretionary.key_information def get_generation_times(self) -> GenerationTimes: """Get timestamps for when keys were generated.""" logger.debug("Getting key generation timestamps") return self.get_application_related_data().discretionary.generation_times def set_generation_time(self, key_ref: KEY_REF, timestamp: int) -> None: """Set the generation timestamp for a key. Requires Admin PIN verification. :param key_ref: The key slot. :param timestamp: The timestamp. """ logger.debug(f"Setting key generation timestamp for {key_ref.name}") self.put_data(key_ref.generation_time_do, struct.pack(">I", timestamp)) logger.info(f"Key generation timestamp set for {key_ref.name}") def get_fingerprints(self) -> Fingerprints: """Get key fingerprints.""" logger.debug("Getting key fingerprints") return self.get_application_related_data().discretionary.fingerprints def set_fingerprint(self, key_ref: KEY_REF, fingerprint: bytes) -> None: """Set the fingerprint for a key. Requires Admin PIN verification. :param key_ref: The key slot. :param fingerprint: The fingerprint. """ logger.debug(f"Setting key fingerprint for {key_ref.name}") self.put_data(key_ref.fingerprint_do, fingerprint) logger.info("Key fingerprint set for {key_ref.name}") def get_public_key(self, key_ref: KEY_REF) -> PublicKey: """Get the public key from a slot. :param key_ref: The key slot. """ logger.debug(f"Getting public key for {key_ref.name}") resp = self.protocol.send_apdu(0, INS.GENERATE_ASYM, 0x81, 0x00, key_ref.crt) data = Tlv.parse_dict(Tlv.unpack(TAG_PUBLIC_KEY, resp)) attributes = self.get_algorithm_attributes(key_ref) if isinstance(attributes, EcAttributes): return _parse_ec_key(attributes.oid, data) else: # RSA return _parse_rsa_key(data) def generate_rsa_key( self, key_ref: KEY_REF, key_size: RSA_SIZE ) -> rsa.RSAPublicKey: """Generate an RSA key in the given slot. Requires Admin PIN verification. :param key_ref: The key slot. :param key_size: The size of the RSA key. """ if (4, 2, 0) <= self.version < (4, 3, 5): raise NotSupportedError("RSA key generation not supported on this YubiKey") logger.debug(f"Generating RSA private key for {key_ref.name}") if ( EXTENDED_CAPABILITY_FLAGS.ALGORITHM_ATTRIBUTES_CHANGEABLE in self.extended_capabilities.flags ): attributes = RsaAttributes.create(key_size) self.set_algorithm_attributes(key_ref, attributes) elif key_size != RSA_SIZE.RSA2048: raise NotSupportedError("Algorithm attributes not supported") resp = self.protocol.send_apdu(0, INS.GENERATE_ASYM, 0x80, 0x00, key_ref.crt) data = Tlv.parse_dict(Tlv.unpack(TAG_PUBLIC_KEY, resp)) logger.info(f"RSA key generated for {key_ref.name}") return _parse_rsa_key(data) def generate_ec_key(self, key_ref: KEY_REF, curve_oid: CurveOid) -> EcPublicKey: """Generate an EC key in the given slot. Requires Admin PIN verification. :param key_ref: The key slot. :param curve_oid: The curve OID. """ require_version(self.version, (5, 2, 0)) if curve_oid not in OID: raise ValueError("Curve OID is not recognized") logger.debug(f"Generating EC private key for {key_ref.name}") attributes = EcAttributes.create(key_ref, curve_oid) self.set_algorithm_attributes(key_ref, attributes) resp = self.protocol.send_apdu(0, INS.GENERATE_ASYM, 0x80, 0x00, key_ref.crt) data = Tlv.parse_dict(Tlv.unpack(TAG_PUBLIC_KEY, resp)) logger.info(f"EC key generated for {key_ref.name}") return _parse_ec_key(curve_oid, data) def put_key(self, key_ref: KEY_REF, private_key: PrivateKey) -> None: """Import a private key into the given slot. Requires Admin PIN verification. :param key_ref: The key slot. :param private_key: The private key to import. """ logger.debug(f"Importing a private key for {key_ref.name}") attributes = _get_key_attributes(private_key, key_ref, self.version) if ( EXTENDED_CAPABILITY_FLAGS.ALGORITHM_ATTRIBUTES_CHANGEABLE in self.extended_capabilities.flags ): self.set_algorithm_attributes(key_ref, attributes) else: if not ( isinstance(attributes, RsaAttributes) and attributes.n_len == RSA_SIZE.RSA2048 ): raise NotSupportedError("This YubiKey only supports RSA 2048 keys") template = _get_key_template(private_key, key_ref, self.version < (4, 0, 0)) self.protocol.send_apdu(0, INS.PUT_DATA_ODD, 0x3F, 0xFF, bytes(template)) logger.info(f"Private key imported for {key_ref.name}") def delete_key(self, key_ref: KEY_REF) -> None: """Delete the contents of a key slot. Requires Admin PIN verification. :param key_ref: The key slot. """ if self.version < (4, 0, 0): # Import over the key self.put_key( key_ref, rsa.generate_private_key(65537, 2048, default_backend()) ) else: # Delete key by changing the key attributes twice. self.put_data( # Use put_data to avoid checking for RSA 4096 support key_ref.algorithm_attributes_do, RsaAttributes.create(RSA_SIZE.RSA4096) ) self.set_algorithm_attributes( key_ref, RsaAttributes.create(RSA_SIZE.RSA2048) ) def _select_certificate(self, key_ref: KEY_REF) -> None: logger.debug(f"Selecting certificate for key {key_ref.name}") try: require_version(self.version, (5, 2, 0)) data: bytes = Tlv(0x60, Tlv(0x5C, int2bytes(DO.CARDHOLDER_CERTIFICATE))) if self.version <= (5, 4, 3): # These use a non-standard byte in the command. data = b"\x06" + data # 6 is the length of the data. self.protocol.send_apdu( 0, INS.SELECT_DATA, 3 - key_ref, 0x04, data, ) except NotSupportedError: if key_ref == KEY_REF.AUT: return # Older version still support AUT, which is the default slot. raise def get_certificate(self, key_ref: KEY_REF) -> x509.Certificate: """Get a certificate from a slot. :param key_ref: The slot. """ logger.debug(f"Getting certificate for key {key_ref.name}") if key_ref == KEY_REF.ATT: require_version(self.version, (5, 2, 0)) data = self.get_data(DO.ATT_CERTIFICATE) else: self._select_certificate(key_ref) data = self.get_data(DO.CARDHOLDER_CERTIFICATE) if not data: raise ValueError("No certificate found!") return x509.load_der_x509_certificate(data, default_backend()) def put_certificate(self, key_ref: KEY_REF, certificate: x509.Certificate) -> None: """Import a certificate into a slot. Requires Admin PIN verification. :param key_ref: The slot. :param certificate: The X.509 certificate to import. """ cert_data = certificate.public_bytes(Encoding.DER) logger.debug(f"Importing certificate for key {key_ref.name}") if key_ref == KEY_REF.ATT: require_version(self.version, (5, 2, 0)) self.put_data(DO.ATT_CERTIFICATE, cert_data) else: self._select_certificate(key_ref) self.put_data(DO.CARDHOLDER_CERTIFICATE, cert_data) logger.info(f"Certificate imported for key {key_ref.name}") def delete_certificate(self, key_ref: KEY_REF) -> None: """Delete a certificate in a slot. Requires Admin PIN verification. :param key_ref: The slot. """ logger.debug(f"Deleting certificate for key {key_ref.name}") if key_ref == KEY_REF.ATT: require_version(self.version, (5, 2, 0)) self.put_data(DO.ATT_CERTIFICATE, b"") else: self._select_certificate(key_ref) self.put_data(DO.CARDHOLDER_CERTIFICATE, b"") logger.info(f"Certificate deleted for key {key_ref.name}") def attest_key(self, key_ref: KEY_REF) -> x509.Certificate: """Create an attestation certificate for a key. The certificte is written to the certificate slot for the key, and its content is returned. Requires User PIN verification. :param key_ref: The key slot. """ require_version(self.version, (5, 2, 0)) logger.debug(f"Attesting key {key_ref.name}") self.protocol.send_apdu(0x80, INS.GET_ATTESTATION, key_ref, 0) logger.info(f"Attestation certificate created for {key_ref.name}") return self.get_certificate(key_ref) def sign(self, message: bytes, hash_algorithm: hashes.HashAlgorithm) -> bytes: """Sign a message using the SIG key. Requires User PIN verification. :param message: The message to sign. :param hash_algorithm: The pre-signature hash algorithm. """ attributes = self.get_algorithm_attributes(KEY_REF.SIG) padded = _pad_message(attributes, message, hash_algorithm) logger.debug(f"Signing a message with {attributes}") response = self.protocol.send_apdu(0, INS.PSO, 0x9E, 0x9A, padded) logger.info("Message signed") if attributes.algorithm_id == 0x13: ln = len(response) // 2 return encode_dss_signature( int.from_bytes(response[:ln], "big"), int.from_bytes(response[ln:], "big"), ) return response def decrypt(self, value: Union[bytes, EcPublicKey]) -> bytes: """Decrypt a value using the DEC key. For RSA the `value` should be an encrypted block. For ECDH the `value` should be a peer public-key to perform the key exchange with, and the result will be the derived shared secret. Requires (extended) User PIN verification. :param value: The value to decrypt. """ attributes = self.get_algorithm_attributes(KEY_REF.DEC) logger.debug(f"Decrypting a value with {attributes}") if isinstance(value, ec.EllipticCurvePublicKey): data = value.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) elif isinstance(value, x25519.X25519PublicKey): data = value.public_bytes(Encoding.Raw, PublicFormat.Raw) elif isinstance(value, bytes): data = value if isinstance(attributes, RsaAttributes): data = b"\0" + data elif isinstance(attributes, EcAttributes): data = Tlv(0xA6, Tlv(0x7F49, Tlv(0x86, data))) response = self.protocol.send_apdu(0, INS.PSO, 0x80, 0x86, data) logger.info("Value decrypted") return response def authenticate( self, message: bytes, hash_algorithm: hashes.HashAlgorithm ) -> bytes: """Authenticate a message using the AUT key. Requires User PIN verification. :param message: The message to authenticate. :param hash_algorithm: The pre-authentication hash algorithm. """ attributes = self.get_algorithm_attributes(KEY_REF.AUT) padded = _pad_message(attributes, message, hash_algorithm) logger.debug(f"Authenticating a message with {attributes}") response = self.protocol.send_apdu( 0, INS.INTERNAL_AUTHENTICATE, 0x0, 0x0, padded ) logger.info("Message authenticated") if attributes.algorithm_id == 0x13: ln = len(response) // 2 return encode_dss_signature( int.from_bytes(response[:ln], "big"), int.from_bytes(response[ln:], "big"), ) return response
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/openpgp.py
openpgp.py
from .core import ( require_version as _require_version, int2bytes, bytes2int, Version, Tlv, NotSupportedError, BadResponseError, InvalidPinError, ) from .core.smartcard import ( SW, AID, ApduError, ApduFormat, SmartCardConnection, SmartCardProtocol, ) from cryptography import x509 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.constant_time import bytes_eq from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from cryptography.hazmat.primitives.asymmetric import rsa, ec from cryptography.hazmat.primitives.asymmetric.padding import AsymmetricPadding from cryptography.hazmat.primitives.asymmetric.utils import Prehashed from cryptography.hazmat.backends import default_backend from dataclasses import dataclass from enum import Enum, IntEnum, unique from typing import Optional, Union, Type, cast import logging import gzip import os import re logger = logging.getLogger(__name__) @unique class ALGORITHM(str, Enum): EC = "ec" RSA = "rsa" # Don't treat pre 1.0 versions as "developer builds". def require_version(my_version: Version, *args, **kwargs): if my_version <= (0, 1, 4): # Last pre 1.0 release of ykneo-piv my_version = Version(1, 0, 0) _require_version(my_version, *args, **kwargs) @unique class KEY_TYPE(IntEnum): RSA1024 = 0x06 RSA2048 = 0x07 ECCP256 = 0x11 ECCP384 = 0x14 @property def algorithm(self): return ALGORITHM.EC if self.name.startswith("ECC") else ALGORITHM.RSA @property def bit_len(self): match = re.search(r"\d+$", self.name) if match: return int(match.group()) raise ValueError("No bit_len") @classmethod def from_public_key(cls, key): if isinstance(key, rsa.RSAPublicKey): try: return getattr(cls, "RSA%d" % key.key_size) except AttributeError: raise ValueError("Unsupported RSA key size: %d" % key.key_size) pass # Fall through to ValueError elif isinstance(key, ec.EllipticCurvePublicKey): curve_name = key.curve.name if curve_name == "secp256r1": return cls.ECCP256 elif curve_name == "secp384r1": return cls.ECCP384 raise ValueError(f"Unsupported EC curve: {curve_name}") raise ValueError(f"Unsupported key type: {type(key).__name__}") @unique class MANAGEMENT_KEY_TYPE(IntEnum): TDES = 0x03 AES128 = 0x08 AES192 = 0x0A AES256 = 0x0C @property def key_len(self): if self.name == "TDES": return 24 # AES return int(self.name[3:]) // 8 @property def challenge_len(self): if self.name == "TDES": return 8 return 16 def _parse_management_key(key_type, management_key): if key_type == MANAGEMENT_KEY_TYPE.TDES: return algorithms.TripleDES(management_key) else: return algorithms.AES(management_key) # The card management slot is special, we don't include it in SLOT below SLOT_CARD_MANAGEMENT = 0x9B @unique class SLOT(IntEnum): AUTHENTICATION = 0x9A SIGNATURE = 0x9C KEY_MANAGEMENT = 0x9D CARD_AUTH = 0x9E RETIRED1 = 0x82 RETIRED2 = 0x83 RETIRED3 = 0x84 RETIRED4 = 0x85 RETIRED5 = 0x86 RETIRED6 = 0x87 RETIRED7 = 0x88 RETIRED8 = 0x89 RETIRED9 = 0x8A RETIRED10 = 0x8B RETIRED11 = 0x8C RETIRED12 = 0x8D RETIRED13 = 0x8E RETIRED14 = 0x8F RETIRED15 = 0x90 RETIRED16 = 0x91 RETIRED17 = 0x92 RETIRED18 = 0x93 RETIRED19 = 0x94 RETIRED20 = 0x95 ATTESTATION = 0xF9 def __str__(self) -> str: return f"{int(self):02X} ({self.name})" @unique class OBJECT_ID(IntEnum): CAPABILITY = 0x5FC107 CHUID = 0x5FC102 AUTHENTICATION = 0x5FC105 # cert for 9a key FINGERPRINTS = 0x5FC103 SECURITY = 0x5FC106 FACIAL = 0x5FC108 PRINTED = 0x5FC109 SIGNATURE = 0x5FC10A # cert for 9c key KEY_MANAGEMENT = 0x5FC10B # cert for 9d key CARD_AUTH = 0x5FC101 # cert for 9e key DISCOVERY = 0x7E KEY_HISTORY = 0x5FC10C IRIS = 0x5FC121 RETIRED1 = 0x5FC10D RETIRED2 = 0x5FC10E RETIRED3 = 0x5FC10F RETIRED4 = 0x5FC110 RETIRED5 = 0x5FC111 RETIRED6 = 0x5FC112 RETIRED7 = 0x5FC113 RETIRED8 = 0x5FC114 RETIRED9 = 0x5FC115 RETIRED10 = 0x5FC116 RETIRED11 = 0x5FC117 RETIRED12 = 0x5FC118 RETIRED13 = 0x5FC119 RETIRED14 = 0x5FC11A RETIRED15 = 0x5FC11B RETIRED16 = 0x5FC11C RETIRED17 = 0x5FC11D RETIRED18 = 0x5FC11E RETIRED19 = 0x5FC11F RETIRED20 = 0x5FC120 ATTESTATION = 0x5FFF01 @classmethod def from_slot(cls, slot): return getattr(cls, SLOT(slot).name) @unique class PIN_POLICY(IntEnum): DEFAULT = 0x0 NEVER = 0x1 ONCE = 0x2 ALWAYS = 0x3 @unique class TOUCH_POLICY(IntEnum): DEFAULT = 0x0 NEVER = 0x1 ALWAYS = 0x2 CACHED = 0x3 # 010203040506070801020304050607080102030405060708 DEFAULT_MANAGEMENT_KEY = ( b"\x01\x02\x03\x04\x05\x06\x07\x08" + b"\x01\x02\x03\x04\x05\x06\x07\x08" + b"\x01\x02\x03\x04\x05\x06\x07\x08" ) PIN_LEN = 8 # Instruction set INS_VERIFY = 0x20 INS_CHANGE_REFERENCE = 0x24 INS_RESET_RETRY = 0x2C INS_GENERATE_ASYMMETRIC = 0x47 INS_AUTHENTICATE = 0x87 INS_GET_DATA = 0xCB INS_PUT_DATA = 0xDB INS_GET_METADATA = 0xF7 INS_ATTEST = 0xF9 INS_SET_PIN_RETRIES = 0xFA INS_RESET = 0xFB INS_GET_VERSION = 0xFD INS_IMPORT_KEY = 0xFE INS_SET_MGMKEY = 0xFF # Tags for parsing responses and preparing requests TAG_AUTH_WITNESS = 0x80 TAG_AUTH_CHALLENGE = 0x81 TAG_AUTH_RESPONSE = 0x82 TAG_AUTH_EXPONENTIATION = 0x85 TAG_GEN_ALGORITHM = 0x80 TAG_OBJ_DATA = 0x53 TAG_OBJ_ID = 0x5C TAG_CERTIFICATE = 0x70 TAG_CERT_INFO = 0x71 TAG_DYN_AUTH = 0x7C TAG_LRC = 0xFE TAG_PIN_POLICY = 0xAA TAG_TOUCH_POLICY = 0xAB # Metadata tags TAG_METADATA_ALGO = 0x01 TAG_METADATA_POLICY = 0x02 TAG_METADATA_ORIGIN = 0x03 TAG_METADATA_PUBLIC_KEY = 0x04 TAG_METADATA_IS_DEFAULT = 0x05 TAG_METADATA_RETRIES = 0x06 ORIGIN_GENERATED = 1 ORIGIN_IMPORTED = 2 INDEX_PIN_POLICY = 0 INDEX_TOUCH_POLICY = 1 INDEX_RETRIES_TOTAL = 0 INDEX_RETRIES_REMAINING = 1 PIN_P2 = 0x80 PUK_P2 = 0x81 def _pin_bytes(pin): pin = pin.encode() if len(pin) > PIN_LEN: raise ValueError("PIN/PUK must be no longer than 8 bytes") return pin.ljust(PIN_LEN, b"\xff") def _retries_from_sw(sw): if sw == SW.AUTH_METHOD_BLOCKED: return 0 if sw & 0xFFF0 == 0x63C0: return sw & 0x0F elif sw & 0xFF00 == 0x6300: return sw & 0xFF return None @dataclass class PinMetadata: default_value: bool total_attempts: int attempts_remaining: int @dataclass class ManagementKeyMetadata: key_type: MANAGEMENT_KEY_TYPE default_value: bool touch_policy: TOUCH_POLICY @dataclass class SlotMetadata: key_type: KEY_TYPE pin_policy: PIN_POLICY touch_policy: TOUCH_POLICY generated: bool public_key_encoded: bytes @property def public_key(self): return _parse_device_public_key(self.key_type, self.public_key_encoded) def _pad_message(key_type, message, hash_algorithm, padding): if key_type.algorithm == ALGORITHM.EC: if isinstance(hash_algorithm, Prehashed): hashed = message else: h = hashes.Hash(hash_algorithm, default_backend()) h.update(message) hashed = h.finalize() byte_len = key_type.bit_len // 8 if len(hashed) < byte_len: return hashed.rjust(byte_len // 8, b"\0") return hashed[:byte_len] elif key_type.algorithm == ALGORITHM.RSA: # Sign with a dummy key, then encrypt the signature to get the padded message e = 65537 dummy = rsa.generate_private_key(e, key_type.bit_len, default_backend()) signature = dummy.sign(message, padding, hash_algorithm) # Raw (textbook) RSA encrypt n = dummy.public_key().public_numbers().n return int2bytes(pow(bytes2int(signature), e, n), key_type.bit_len // 8) def _unpad_message(padded, padding): e = 65537 dummy = rsa.generate_private_key(e, len(padded) * 8, default_backend()) # Raw (textbook) RSA encrypt n = dummy.public_key().public_numbers().n encrypted = int2bytes(pow(bytes2int(padded), e, n), len(padded)) return dummy.decrypt(encrypted, padding) def check_key_support( version: Version, key_type: KEY_TYPE, pin_policy: PIN_POLICY, touch_policy: TOUCH_POLICY, generate: bool = True, ) -> None: """Check if a key type is supported by a specific YubiKey firmware version. This method will return None if the key (with PIN and touch policies) is supported, or it will raise a NotSupportedError if it is not. """ if version[0] == 0 and version > (0, 1, 3): return # Development build, skip version checks if version < (4, 0, 0): if key_type == KEY_TYPE.ECCP384: raise NotSupportedError("ECCP384 requires YubiKey 4 or later") if touch_policy != TOUCH_POLICY.DEFAULT or pin_policy != PIN_POLICY.DEFAULT: raise NotSupportedError("PIN/Touch policy requires YubiKey 4 or later") if version < (4, 3, 0) and touch_policy == TOUCH_POLICY.CACHED: raise NotSupportedError("Cached touch policy requires YubiKey 4.3 or later") # ROCA if (4, 2, 0) <= version < (4, 3, 5): if generate and key_type.algorithm == ALGORITHM.RSA: raise NotSupportedError("RSA key generation not supported on this YubiKey") # FIPS if (4, 4, 0) <= version < (4, 5, 0): if key_type == KEY_TYPE.RSA1024: raise NotSupportedError("RSA 1024 not supported on YubiKey FIPS") if pin_policy == PIN_POLICY.NEVER: raise NotSupportedError("PIN_POLICY.NEVER not allowed on YubiKey FIPS") def _parse_device_public_key(key_type, encoded): data = Tlv.parse_dict(encoded) if key_type.algorithm == ALGORITHM.RSA: modulus = bytes2int(data[0x81]) exponent = bytes2int(data[0x82]) return rsa.RSAPublicNumbers(exponent, modulus).public_key(default_backend()) else: if key_type == KEY_TYPE.ECCP256: curve: Type[ec.EllipticCurve] = ec.SECP256R1 else: curve = ec.SECP384R1 return ec.EllipticCurvePublicKey.from_encoded_point(curve(), data[0x86]) class PivSession: """A session with the PIV application.""" def __init__(self, connection: SmartCardConnection): self.protocol = SmartCardProtocol(connection) self.protocol.select(AID.PIV) self._version = Version.from_bytes( self.protocol.send_apdu(0, INS_GET_VERSION, 0, 0) ) self.protocol.enable_touch_workaround(self.version) if self.version >= (4, 0, 0): self.protocol.apdu_format = ApduFormat.EXTENDED self._current_pin_retries = 3 self._max_pin_retries = 3 logger.debug(f"PIV session initialized (version={self.version})") @property def version(self) -> Version: return self._version def reset(self) -> None: logger.debug("Preparing PIV reset") # Block PIN logger.debug("Verify PIN with invalid attempts until blocked") counter = self.get_pin_attempts() while counter > 0: try: self.verify_pin("") except InvalidPinError as e: counter = e.attempts_remaining logger.debug("PIN is blocked") # Block PUK logger.debug("Verify PUK with invalid attempts until blocked") counter = 1 while counter > 0: try: self._change_reference(INS_RESET_RETRY, PIN_P2, "", "") except InvalidPinError as e: counter = e.attempts_remaining logger.debug("PUK is blocked") # Reset logger.debug("Sending reset") self.protocol.send_apdu(0, INS_RESET, 0, 0) self._current_pin_retries = 3 self._max_pin_retries = 3 logger.info("PIV application data reset performed") def authenticate( self, key_type: MANAGEMENT_KEY_TYPE, management_key: bytes ) -> None: """Authenticate to PIV with management key. :param key_type: The management key type. :param management_key: The management key in raw bytes. """ key_type = MANAGEMENT_KEY_TYPE(key_type) logger.debug(f"Authenticating with key type: {key_type}") response = self.protocol.send_apdu( 0, INS_AUTHENTICATE, key_type, SLOT_CARD_MANAGEMENT, Tlv(TAG_DYN_AUTH, Tlv(TAG_AUTH_WITNESS)), ) witness = Tlv.unpack(TAG_AUTH_WITNESS, Tlv.unpack(TAG_DYN_AUTH, response)) challenge = os.urandom(key_type.challenge_len) backend = default_backend() cipher_key = _parse_management_key(key_type, management_key) cipher = Cipher(cipher_key, modes.ECB(), backend) # nosec decryptor = cipher.decryptor() decrypted = decryptor.update(witness) + decryptor.finalize() response = self.protocol.send_apdu( 0, INS_AUTHENTICATE, key_type, SLOT_CARD_MANAGEMENT, Tlv( TAG_DYN_AUTH, Tlv(TAG_AUTH_WITNESS, decrypted) + Tlv(TAG_AUTH_CHALLENGE, challenge), ), ) encrypted = Tlv.unpack(TAG_AUTH_RESPONSE, Tlv.unpack(TAG_DYN_AUTH, response)) encryptor = cipher.encryptor() expected = encryptor.update(challenge) + encryptor.finalize() if not bytes_eq(expected, encrypted): raise BadResponseError("Device response is incorrect") def set_management_key( self, key_type: MANAGEMENT_KEY_TYPE, management_key: bytes, require_touch: bool = False, ) -> None: """Set a new management key. :param key_type: The management key type. :param management_key: The management key in raw bytes. :param require_touch: The touch policy. """ key_type = MANAGEMENT_KEY_TYPE(key_type) logger.debug(f"Setting management key of type: {key_type}") if key_type != MANAGEMENT_KEY_TYPE.TDES: require_version(self.version, (5, 4, 0)) if len(management_key) != key_type.key_len: raise ValueError("Management key must be %d bytes" % key_type.key_len) self.protocol.send_apdu( 0, INS_SET_MGMKEY, 0xFF, 0xFE if require_touch else 0xFF, int2bytes(key_type) + Tlv(SLOT_CARD_MANAGEMENT, management_key), ) logger.info("Management key set") def verify_pin(self, pin: str) -> None: """Verify the PIN. :param pin: The PIN. """ logger.debug("Verifying PIN") try: self.protocol.send_apdu(0, INS_VERIFY, 0, PIN_P2, _pin_bytes(pin)) self._current_pin_retries = self._max_pin_retries except ApduError as e: retries = _retries_from_sw(e.sw) if retries is None: raise self._current_pin_retries = retries raise InvalidPinError(retries) def get_pin_attempts(self) -> int: """Get remaining PIN attempts.""" logger.debug("Getting PIN attempts") try: return self.get_pin_metadata().attempts_remaining except NotSupportedError: try: self.protocol.send_apdu(0, INS_VERIFY, 0, PIN_P2) # Already verified, no way to know true count logger.debug("Using cached value, may be incorrect.") return self._current_pin_retries except ApduError as e: retries = _retries_from_sw(e.sw) if retries is None: raise self._current_pin_retries = retries logger.debug("Using value from empty verify") return retries def change_pin(self, old_pin: str, new_pin: str) -> None: """Change the PIN. :param old_pin: The current PIN. :param new_pin: The new PIN. """ logger.debug("Changing PIN") self._change_reference(INS_CHANGE_REFERENCE, PIN_P2, old_pin, new_pin) logger.info("New PIN set") def change_puk(self, old_puk: str, new_puk: str) -> None: """Change the PUK. :param old_puk: The current PUK. :param new_puk: The new PUK. """ logger.debug("Changing PUK") self._change_reference(INS_CHANGE_REFERENCE, PUK_P2, old_puk, new_puk) logger.info("New PUK set") def unblock_pin(self, puk: str, new_pin: str) -> None: """Reset PIN with PUK. :param puk: The PUK. :param new_pin: The new PIN. """ logger.debug("Using PUK to set new PIN") self._change_reference(INS_RESET_RETRY, PIN_P2, puk, new_pin) logger.info("New PIN set") def set_pin_attempts(self, pin_attempts: int, puk_attempts: int) -> None: """Set PIN retries for PIN and PUK. Both PIN and PUK will be reset to default values when this is executed. Requires authentication with management key and PIN verification. :param pin_attempts: The PIN attempts. :param puk_attempts: The PUK attempts. """ logger.debug(f"Setting PIN/PUK attempts ({pin_attempts}, {puk_attempts})") try: self.protocol.send_apdu(0, INS_SET_PIN_RETRIES, pin_attempts, puk_attempts) self._max_pin_retries = pin_attempts self._current_pin_retries = pin_attempts logger.info("PIN/PUK attempts set") except ApduError as e: if e.sw == SW.INVALID_INSTRUCTION: raise NotSupportedError( "Setting PIN attempts not supported on this YubiKey" ) raise def get_pin_metadata(self) -> PinMetadata: """Get PIN metadata.""" logger.debug("Getting PIN metadata") return self._get_pin_puk_metadata(PIN_P2) def get_puk_metadata(self) -> PinMetadata: """Get PUK metadata.""" logger.debug("Getting PUK metadata") return self._get_pin_puk_metadata(PUK_P2) def get_management_key_metadata(self) -> ManagementKeyMetadata: """Get management key metadata.""" logger.debug("Getting management key metadata") require_version(self.version, (5, 3, 0)) data = Tlv.parse_dict( self.protocol.send_apdu(0, INS_GET_METADATA, 0, SLOT_CARD_MANAGEMENT) ) policy = data[TAG_METADATA_POLICY] return ManagementKeyMetadata( MANAGEMENT_KEY_TYPE(data.get(TAG_METADATA_ALGO, b"\x03")[0]), data[TAG_METADATA_IS_DEFAULT] != b"\0", TOUCH_POLICY(policy[INDEX_TOUCH_POLICY]), ) def get_slot_metadata(self, slot: SLOT) -> SlotMetadata: """Get slot metadata. :param slot: The slot to get metadata from. """ slot = SLOT(slot) logger.debug(f"Getting metadata for slot {slot}") require_version(self.version, (5, 3, 0)) data = Tlv.parse_dict(self.protocol.send_apdu(0, INS_GET_METADATA, 0, slot)) policy = data[TAG_METADATA_POLICY] return SlotMetadata( KEY_TYPE(data[TAG_METADATA_ALGO][0]), PIN_POLICY(policy[INDEX_PIN_POLICY]), TOUCH_POLICY(policy[INDEX_TOUCH_POLICY]), data[TAG_METADATA_ORIGIN][0] == ORIGIN_GENERATED, data[TAG_METADATA_PUBLIC_KEY], ) def sign( self, slot: SLOT, key_type: KEY_TYPE, message: bytes, hash_algorithm: hashes.HashAlgorithm, padding: Optional[AsymmetricPadding] = None, ) -> bytes: """Sign message with key. Requires PIN verification. :param slot: The slot of the key to use. :param key_type: The type of the key to sign with. :param message: The message to sign. :param hash_algorithm: The pre-signature hash algorithm to use. :param padding: The pre-signature padding. """ slot = SLOT(slot) key_type = KEY_TYPE(key_type) logger.debug( f"Signing data with key in slot {slot} of type {key_type} using " f"hash={hash_algorithm}, padding={padding}" ) padded = _pad_message(key_type, message, hash_algorithm, padding) return self._use_private_key(slot, key_type, padded, False) def decrypt( self, slot: SLOT, cipher_text: bytes, padding: AsymmetricPadding ) -> bytes: """Decrypt cipher text. Requires PIN verification. :param slot: The slot. :param cipher_text: The cipher text to decrypt. :param padding: The padding of the plain text. """ slot = SLOT(slot) if len(cipher_text) == 1024 // 8: key_type = KEY_TYPE.RSA1024 elif len(cipher_text) == 2048 // 8: key_type = KEY_TYPE.RSA2048 else: raise ValueError("Invalid length of ciphertext") logger.debug( f"Decrypting data with key in slot {slot} of type {key_type} using ", f"padding={padding}", ) padded = self._use_private_key(slot, key_type, cipher_text, False) return _unpad_message(padded, padding) def calculate_secret( self, slot: SLOT, peer_public_key: ec.EllipticCurvePublicKey ) -> bytes: """Calculate shared secret using ECDH. Requires PIN verification. :param slot: The slot. :param peer_public_key: The peer's public key. """ slot = SLOT(slot) key_type = KEY_TYPE.from_public_key(peer_public_key) if key_type.algorithm != ALGORITHM.EC: raise ValueError("Unsupported key type") logger.debug( f"Performing key agreement with key in slot {slot} of type {key_type}" ) data = peer_public_key.public_bytes( Encoding.X962, PublicFormat.UncompressedPoint ) return self._use_private_key(slot, key_type, data, True) def get_object(self, object_id: int) -> bytes: """Get object by ID. Requires PIN verification. :param object_id: The object identifier. """ logger.debug(f"Reading data from object slot {hex(object_id)}") if object_id == OBJECT_ID.DISCOVERY: expected: int = OBJECT_ID.DISCOVERY else: expected = TAG_OBJ_DATA try: return Tlv.unpack( expected, self.protocol.send_apdu( 0, INS_GET_DATA, 0x3F, 0xFF, Tlv(TAG_OBJ_ID, int2bytes(object_id)), ), ) except ValueError as e: raise BadResponseError("Malformed object data", e) def put_object(self, object_id: int, data: Optional[bytes] = None) -> None: """Write data to PIV object. Requires authentication with management key. :param object_id: The object identifier. :param data: The object data. """ self.protocol.send_apdu( 0, INS_PUT_DATA, 0x3F, 0xFF, Tlv(TAG_OBJ_ID, int2bytes(object_id)) + Tlv(TAG_OBJ_DATA, data or b""), ) logger.info(f"Data written to object slot {hex(object_id)}") def get_certificate(self, slot: SLOT) -> x509.Certificate: """Get certificate from slot. :param slot: The slot to get the certificate from. """ slot = SLOT(slot) logger.debug(f"Reading certificate in slot {slot}") try: data = Tlv.parse_dict(self.get_object(OBJECT_ID.from_slot(slot))) except ValueError: raise BadResponseError("Malformed certificate data object") cert_data = data[TAG_CERTIFICATE] cert_info = data[TAG_CERT_INFO][0] if TAG_CERT_INFO in data else 0 if cert_info == 1: logger.debug("Certificate is compressed, decompressing...") # Compressed certificate cert_data = gzip.decompress(cert_data) elif cert_info != 0: raise NotSupportedError("Unsupported value in CertInfo") try: return x509.load_der_x509_certificate(cert_data, default_backend()) except Exception as e: raise BadResponseError("Invalid certificate", e) def put_certificate( self, slot: SLOT, certificate: x509.Certificate, compress: bool = False ) -> None: """Import certificate to slot. Requires authentication with management key. :param slot: The slot to import the certificate to. :param certificate: The certificate to import. :param compress: If the certificate should be compressed or not. """ slot = SLOT(slot) logger.debug(f"Storing certificate in slot {slot}") cert_data = certificate.public_bytes(Encoding.DER) logger.debug(f"Certificate is {len(cert_data)} bytes, compression={compress}") if compress: cert_info = b"\1" cert_data = gzip.compress(cert_data) logger.debug(f"Compressed size: {len(cert_data)} bytes") else: cert_info = b"\0" data = ( Tlv(TAG_CERTIFICATE, cert_data) + Tlv(TAG_CERT_INFO, cert_info) + Tlv(TAG_LRC) ) self.put_object(OBJECT_ID.from_slot(slot), data) logger.info(f"Certificate written to slot {slot}, compression={compress}") def delete_certificate(self, slot: SLOT) -> None: """Delete certificate. Requires authentication with management key. :param slot: The slot to delete the certificate from. """ slot = SLOT(slot) logger.debug(f"Deleting certificate in slot {slot}") self.put_object(OBJECT_ID.from_slot(slot)) def put_key( self, slot: SLOT, private_key: Union[ rsa.RSAPrivateKeyWithSerialization, ec.EllipticCurvePrivateKeyWithSerialization, ], pin_policy: PIN_POLICY = PIN_POLICY.DEFAULT, touch_policy: TOUCH_POLICY = TOUCH_POLICY.DEFAULT, ) -> None: """Import a private key to slot. Requires authentication with management key. :param slot: The slot to import the key to. :param private_key: The private key to import. :param pin_policy: The PIN policy. :param touch_policy: The touch policy. """ slot = SLOT(slot) key_type = KEY_TYPE.from_public_key(private_key.public_key()) check_key_support(self.version, key_type, pin_policy, touch_policy, False) ln = key_type.bit_len // 8 numbers = private_key.private_numbers() if key_type.algorithm == ALGORITHM.RSA: numbers = cast(rsa.RSAPrivateNumbers, numbers) if numbers.public_numbers.e != 65537: raise NotSupportedError("RSA exponent must be 65537") ln //= 2 data = ( Tlv(0x01, int2bytes(numbers.p, ln)) + Tlv(0x02, int2bytes(numbers.q, ln)) + Tlv(0x03, int2bytes(numbers.dmp1, ln)) + Tlv(0x04, int2bytes(numbers.dmq1, ln)) + Tlv(0x05, int2bytes(numbers.iqmp, ln)) ) else: numbers = cast(ec.EllipticCurvePrivateNumbers, numbers) data = Tlv(0x06, int2bytes(numbers.private_value, ln)) if pin_policy: data += Tlv(TAG_PIN_POLICY, int2bytes(pin_policy)) if touch_policy: data += Tlv(TAG_TOUCH_POLICY, int2bytes(touch_policy)) logger.debug( f"Importing key with pin_policy={pin_policy}, touch_policy={touch_policy}" ) self.protocol.send_apdu(0, INS_IMPORT_KEY, key_type, slot, data) logger.info(f"Private key imported in slot {slot} of type {key_type}") return key_type def generate_key( self, slot: SLOT, key_type: KEY_TYPE, pin_policy: PIN_POLICY = PIN_POLICY.DEFAULT, touch_policy: TOUCH_POLICY = TOUCH_POLICY.DEFAULT, ) -> Union[rsa.RSAPublicKey, ec.EllipticCurvePublicKey]: """Generate private key in slot. Requires authentication with management key. :param slot: The slot to generate the private key in. :param key_type: The key type. :param pin_policy: The PIN policy. :param touch_policy: The touch policy. """ slot = SLOT(slot) key_type = KEY_TYPE(key_type) check_key_support(self.version, key_type, pin_policy, touch_policy, True) data: bytes = Tlv(TAG_GEN_ALGORITHM, int2bytes(key_type)) if pin_policy: data += Tlv(TAG_PIN_POLICY, int2bytes(pin_policy)) if touch_policy: data += Tlv(TAG_TOUCH_POLICY, int2bytes(touch_policy)) logger.debug( f"Generating key with pin_policy={pin_policy}, touch_policy={touch_policy}" ) response = self.protocol.send_apdu( 0, INS_GENERATE_ASYMMETRIC, 0, slot, Tlv(0xAC, data) ) logger.info(f"Private key generated in slot {slot} of type {key_type}") return _parse_device_public_key(key_type, Tlv.unpack(0x7F49, response)) def attest_key(self, slot: SLOT) -> x509.Certificate: """Attest key in slot. :param slot: The slot where the key has been generated. :return: A X.509 certificate. """ require_version(self.version, (4, 3, 0)) slot = SLOT(slot) response = self.protocol.send_apdu(0, INS_ATTEST, slot, 0) logger.debug(f"Attested key in slot {slot}") return x509.load_der_x509_certificate(response, default_backend()) def _change_reference(self, ins, p2, value1, value2): try: self.protocol.send_apdu( 0, ins, 0, p2, _pin_bytes(value1) + _pin_bytes(value2) ) except ApduError as e: retries = _retries_from_sw(e.sw) if retries is None: raise if p2 == PIN_P2: self._current_pin_retries = retries raise InvalidPinError(retries) def _get_pin_puk_metadata(self, p2): require_version(self.version, (5, 3, 0)) data = Tlv.parse_dict(self.protocol.send_apdu(0, INS_GET_METADATA, 0, p2)) attempts = data[TAG_METADATA_RETRIES] return PinMetadata( data[TAG_METADATA_IS_DEFAULT] != b"\0", attempts[INDEX_RETRIES_TOTAL], attempts[INDEX_RETRIES_REMAINING], ) def _use_private_key(self, slot, key_type, message, exponentiation): try: response = self.protocol.send_apdu( 0, INS_AUTHENTICATE, key_type, slot, Tlv( TAG_DYN_AUTH, Tlv(TAG_AUTH_RESPONSE) + Tlv( TAG_AUTH_EXPONENTIATION if exponentiation else TAG_AUTH_CHALLENGE, message, ), ), ) return Tlv.unpack( TAG_AUTH_RESPONSE, Tlv.unpack( TAG_DYN_AUTH, response, ), ) except ApduError as e: if e.sw == SW.INCORRECT_PARAMETERS: raise e # TODO: Different error, No key? raise
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/piv.py
piv.py
from . import Connection, CommandError, TimeoutError, Version, USB_INTERFACE from yubikit.logging import LOG_LEVEL from time import sleep from threading import Event from typing import Optional, Callable import abc import struct import logging logger = logging.getLogger(__name__) MODHEX_ALPHABET = "cbdefghijklnrtuv" class CommandRejectedError(CommandError): """The issues command was rejected by the YubiKey""" class OtpConnection(Connection, metaclass=abc.ABCMeta): usb_interface = USB_INTERFACE.OTP @abc.abstractmethod def receive(self) -> bytes: """Reads an 8 byte feature report""" @abc.abstractmethod def send(self, data: bytes) -> None: """Writes an 8 byte feature report""" CRC_OK_RESIDUAL = 0xF0B8 def calculate_crc(data: bytes) -> int: crc = 0xFFFF for index in range(len(data)): crc ^= data[index] for i in range(8): j = crc & 1 crc >>= 1 if j == 1: crc ^= 0x8408 return crc & 0xFFFF def check_crc(data: bytes) -> bool: return calculate_crc(data) == CRC_OK_RESIDUAL def modhex_encode(data: bytes) -> str: """Encode a bytes-like object using Modhex (modified hexadecimal) encoding.""" return "".join(MODHEX_ALPHABET[b >> 4] + MODHEX_ALPHABET[b & 0xF] for b in data) def modhex_decode(string: str) -> bytes: """Decode the Modhex (modified hexadecimal) string.""" if len(string) % 2: raise ValueError("Length must be a multiple of 2") return bytes( MODHEX_ALPHABET.index(string[i]) << 4 | MODHEX_ALPHABET.index(string[i + 1]) for i in range(0, len(string), 2) ) FEATURE_RPT_SIZE = 8 FEATURE_RPT_DATA_SIZE = FEATURE_RPT_SIZE - 1 SLOT_DATA_SIZE = 64 FRAME_SIZE = SLOT_DATA_SIZE + 6 RESP_PENDING_FLAG = 0x40 # Response pending flag SLOT_WRITE_FLAG = 0x80 # Write flag - set by app - cleared by device RESP_TIMEOUT_WAIT_FLAG = 0x20 # Waiting for timeout operation DUMMY_REPORT_WRITE = 0x8F # Write a dummy report to force update or abort SEQUENCE_MASK = 0x1F STATUS_OFFSET_PROG_SEQ = 0x4 STATUS_OFFSET_TOUCH_LOW = 0x5 CONFIG_STATUS_MASK = 0x1F STATUS_PROCESSING = 1 STATUS_UPNEEDED = 2 def _should_send(packet, seq): """All-zero packets are skipped, except for the very first and last packets""" return seq in (0, 9) or any(packet) def _format_frame(slot, payload): return payload + struct.pack("<BH", slot, calculate_crc(payload)) + b"\0\0\0" class OtpProtocol: """An implementation of the OTP protocol.""" def __init__(self, otp_connection: OtpConnection): self.connection = otp_connection report = self._receive() self.version = Version.from_bytes(report[1:4]) if self.version[0] == 3: # NEO, may have cached pgmSeq in arbitrator try: # Force communication with applet to refresh pgmSeq # Write an invalid scan map, does nothing self.send_and_receive(0x12, b"c" * 51) except CommandRejectedError: pass # This is expected def close(self) -> None: self.connection.close() def send_and_receive( self, slot: int, data: Optional[bytes] = None, event: Optional[Event] = None, on_keepalive: Optional[Callable[[int], None]] = None, ) -> bytes: """Sends a command to the YubiKey, and reads the response. If the command results in a configuration update, the programming sequence number is verified and the updated status bytes are returned. :param slot: The slot to send to. :param data: The data payload to send. :param state: Optional CommandState for listening for user presence requirement and for cancelling a command. :return: Response data (including CRC) in the case of data, or an updated status struct. """ payload = (data or b"").ljust(SLOT_DATA_SIZE, b"\0") if len(payload) > SLOT_DATA_SIZE: raise ValueError("Payload too large for HID frame") if not on_keepalive: on_keepalive = lambda x: None # noqa frame = _format_frame(slot, payload) logger.log(LOG_LEVEL.TRAFFIC, "SEND: %s", frame.hex()) response = self._read_frame( self._send_frame(frame), event or Event(), on_keepalive ) logger.log(LOG_LEVEL.TRAFFIC, "RECV: %s", response.hex()) return response def _receive(self): report = self.connection.receive() if len(report) != FEATURE_RPT_SIZE: raise Exception( f"Incorrect reature report size (was {len(report)}, " f"expected {FEATURE_RPT_SIZE})" ) return report def read_status(self) -> bytes: """Receive status bytes from YubiKey. :return: Status bytes (first 3 bytes are the firmware version). :raises IOException: in case of communication error. """ return self._receive()[1:-1] def _await_ready_to_write(self): """Sleep for up to ~1s waiting for the WRITE flag to be unset""" for _ in range(20): if (self._receive()[FEATURE_RPT_DATA_SIZE] & SLOT_WRITE_FLAG) == 0: return sleep(0.05) raise Exception("Timeout waiting for YubiKey to become ready to receive") def _send_frame(self, buf): """Sends a 70 byte frame""" prog_seq = self._receive()[STATUS_OFFSET_PROG_SEQ] seq = 0 while buf: report, buf = buf[:FEATURE_RPT_DATA_SIZE], buf[FEATURE_RPT_DATA_SIZE:] if _should_send(report, seq): report += struct.pack(">B", 0x80 | seq) self._await_ready_to_write() self.connection.send(report) seq += 1 return prog_seq def _read_frame(self, prog_seq, event, on_keepalive): """Reads one frame""" response = b"" seq = 0 needs_touch = False try: while True: report = self._receive() status_byte = report[FEATURE_RPT_DATA_SIZE] if (status_byte & RESP_PENDING_FLAG) != 0: # Response packet if seq == (status_byte & SEQUENCE_MASK): # Correct sequence response += report[:FEATURE_RPT_DATA_SIZE] seq += 1 elif 0 == (status_byte & SEQUENCE_MASK): # Transmission complete self._reset_state() return response elif status_byte == 0: # Status response next_prog_seq = report[STATUS_OFFSET_PROG_SEQ] if response: raise Exception("Incomplete transfer") elif next_prog_seq == prog_seq + 1 or ( prog_seq > 0 and next_prog_seq == 0 and report[STATUS_OFFSET_TOUCH_LOW] & CONFIG_STATUS_MASK == 0 ): # Note: If no valid configurations exist, prog_seq resets to 0. # Sequence updated, return status. return report[1:-1] elif needs_touch: raise TimeoutError("Timed out waiting for touch") else: raise CommandRejectedError("No data") else: # Need to wait if (status_byte & RESP_TIMEOUT_WAIT_FLAG) != 0: on_keepalive(STATUS_UPNEEDED) needs_touch = True timeout = 0.1 else: on_keepalive(STATUS_PROCESSING) timeout = 0.02 sleep(timeout) if event.wait(timeout): self._reset_state() raise TimeoutError("Command cancelled by Event") except KeyboardInterrupt: logger.debug("Keyboard interrupt, reset state...") self._reset_state() raise def _reset_state(self): """Reset the state of YubiKey from reading""" self.connection.send(b"\xff".rjust(FEATURE_RPT_SIZE, b"\0"))
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/core/otp.py
otp.py
from enum import Enum, IntEnum, IntFlag, unique from typing import ( Type, List, Dict, Tuple, TypeVar, Union, Optional, Hashable, NamedTuple, Callable, ClassVar, ) import re import abc _VERSION_STRING_PATTERN = re.compile(r"\b(?P<major>\d+).(?P<minor>\d).(?P<patch>\d)\b") class Version(NamedTuple): """3-digit version tuple.""" major: int minor: int patch: int def __str__(self): return "%d.%d.%d" % self @classmethod def from_bytes(cls, data: bytes) -> "Version": return cls(*data) @classmethod def from_string(cls, data: str) -> "Version": m = _VERSION_STRING_PATTERN.search(data) if m: return cls( int(m.group("major")), int(m.group("minor")), int(m.group("patch")) ) raise ValueError("No version found in string") @unique class TRANSPORT(str, Enum): """YubiKey physical connection transports.""" USB = "usb" NFC = "nfc" def __str__(self): return super().__str__().upper() @unique class USB_INTERFACE(IntFlag): """YubiKey USB interface identifiers.""" OTP = 0x01 FIDO = 0x02 CCID = 0x04 @unique class YUBIKEY(Enum): """YubiKey hardware platforms.""" YKS = "YubiKey Standard" NEO = "YubiKey NEO" SKY = "Security Key by Yubico" YKP = "YubiKey Plus" YK4 = "YubiKey" # This includes YubiKey 5 class Connection(abc.ABC): """A connection to a YubiKey""" usb_interface: ClassVar[USB_INTERFACE] = USB_INTERFACE(0) def close(self) -> None: """Close the device, releasing any held resources.""" def __enter__(self): return self def __exit__(self, typ, value, traceback): self.close() @unique class PID(IntEnum): """USB Product ID values for YubiKey devices.""" YKS_OTP = 0x0010 NEO_OTP = 0x0110 NEO_OTP_CCID = 0x0111 NEO_CCID = 0x0112 NEO_FIDO = 0x0113 NEO_OTP_FIDO = 0x0114 NEO_FIDO_CCID = 0x0115 NEO_OTP_FIDO_CCID = 0x0116 SKY_FIDO = 0x0120 YK4_OTP = 0x0401 YK4_FIDO = 0x0402 YK4_OTP_FIDO = 0x0403 YK4_CCID = 0x0404 YK4_OTP_CCID = 0x0405 YK4_FIDO_CCID = 0x0406 YK4_OTP_FIDO_CCID = 0x0407 YKP_OTP_FIDO = 0x0410 @property def yubikey_type(self) -> YUBIKEY: return YUBIKEY[self.name.split("_", 1)[0]] @property def usb_interfaces(self) -> USB_INTERFACE: return USB_INTERFACE(sum(USB_INTERFACE[x] for x in self.name.split("_")[1:])) @classmethod def of(cls, key_type: YUBIKEY, interfaces: USB_INTERFACE) -> "PID": suffix = "_".join(t.name or str(t) for t in USB_INTERFACE if t in interfaces) return cls[key_type.name + "_" + suffix] def supports_connection(self, connection_type: Type[Connection]) -> bool: return connection_type.usb_interface in self.usb_interfaces T_Connection = TypeVar("T_Connection", bound=Connection) class YubiKeyDevice(abc.ABC): """YubiKey device reference""" def __init__(self, transport: TRANSPORT, fingerprint: Hashable): self._transport = transport self._fingerprint = fingerprint @property def transport(self) -> TRANSPORT: """Get the transport used to communicate with this YubiKey""" return self._transport def supports_connection(self, connection_type: Type[Connection]) -> bool: """Check if a YubiKeyDevice supports a specific Connection type""" return False # mypy will not accept abstract types in Type[T_Connection] def open_connection( self, connection_type: Union[Type[T_Connection], Callable[..., T_Connection]] ) -> T_Connection: """Opens a connection to the YubiKey""" raise ValueError("Unsupported Connection type") @property def fingerprint(self) -> Hashable: """Used to identify that device references from different enumerations represent the same physical YubiKey. This fingerprint is not stable between sessions, or after un-plugging, and re-plugging a device.""" return self._fingerprint def __eq__(self, other): return isinstance(other, type(self)) and self.fingerprint == other.fingerprint def __hash__(self): return hash(self.fingerprint) def __repr__(self): return f"{type(self).__name__}(fingerprint={self.fingerprint!r})" class CommandError(Exception): """An error response from a YubiKey""" class BadResponseError(CommandError): """Invalid response data from the YubiKey""" class TimeoutError(CommandError): """An operation timed out waiting for something""" class ApplicationNotAvailableError(CommandError): """The application is either disabled or not supported on this YubiKey""" class NotSupportedError(ValueError): """Attempting an action that is not supported on this YubiKey""" class InvalidPinError(CommandError, ValueError): """An incorrect PIN/PUK was used, with the number of attempts now remaining. WARNING: This exception currently inherits from ValueError for backwards-compatibility reasons. This will no longer be the case with the next major version of the library. """ def __init__(self, attempts_remaining: int, message: Optional[str] = None): super().__init__(message or f"Invalid PIN/PUK, {attempts_remaining} remaining") self.attempts_remaining = attempts_remaining def require_version( my_version: Version, min_version: Tuple[int, int, int], message=None ): """Ensure a version is at least min_version.""" # Skip version checks for major == 0, used for development builds. if my_version < min_version and my_version[0] != 0: if not message: message = "This action requires YubiKey %d.%d.%d or later" % min_version raise NotSupportedError(message) def int2bytes(value: int, min_len: int = 0) -> bytes: buf = [] while value > 0xFF: buf.append(value & 0xFF) value >>= 8 buf.append(value) return bytes(reversed(buf)).rjust(min_len, b"\0") def bytes2int(data: bytes) -> int: return int.from_bytes(data, "big") def _tlv_parse(data, offset=0): try: tag = data[offset] offset += 1 if tag & 0x1F == 0x1F: # Long form tag = tag << 8 | data[offset] offset += 1 while tag & 0x80 == 0x80: # Additional bytes tag = tag << 8 | data[offset] offset += 1 ln = data[offset] offset += 1 if ln == 0x80: # Indefinite length end = offset while data[end] or data[end + 1]: # Run until 0x0000 end = _tlv_parse(data, end)[3] # Skip over TLV ln = end - offset end += 2 # End after 0x0000 else: if ln > 0x80: # Length spans multiple bytes n_bytes = ln - 0x80 ln = bytes2int(data[offset : offset + n_bytes]) offset += n_bytes end = offset + ln return tag, offset, ln, end except IndexError: raise ValueError("Invalid encoding of tag/length") T_Tlv = TypeVar("T_Tlv", bound="Tlv") class Tlv(bytes): @property def tag(self) -> int: return self._tag @property def length(self) -> int: return self._value_ln @property def value(self) -> bytes: return self[self._value_offset : self._value_offset + self._value_ln] def __new__(cls, tag_or_data: Union[int, bytes], value: Optional[bytes] = None): """This allows creation by passing either binary data, or tag and value.""" if isinstance(tag_or_data, int): # Tag and (optional) value tag = tag_or_data # Pack into Tlv buf = bytearray() buf.extend(int2bytes(tag)) value = value or b"" length = len(value) if length < 0x80: buf.append(length) else: ln_bytes = int2bytes(length) buf.append(0x80 | len(ln_bytes)) buf.extend(ln_bytes) buf.extend(value) data = bytes(buf) else: # Binary TLV data if value is not None: raise ValueError("value can only be provided if tag_or_data is a tag") data = tag_or_data # mypy thinks this is wrong return super(Tlv, cls).__new__(cls, data) # type: ignore def __init__(self, tag_or_data: Union[int, bytes], value: Optional[bytes] = None): self._tag, self._value_offset, self._value_ln, end = _tlv_parse(self) if len(self) != end: raise ValueError("Incorrect TLV length") def __repr__(self): return f"Tlv(tag=0x{self.tag:02x}, value={self.value.hex()})" @classmethod def parse_from(cls: Type[T_Tlv], data: bytes) -> Tuple[T_Tlv, bytes]: tag, offs, ln, end = _tlv_parse(data) return cls(data[:end]), data[end:] @classmethod def parse_list(cls: Type[T_Tlv], data: bytes) -> List[T_Tlv]: res = [] while data: tlv, data = cls.parse_from(data) res.append(tlv) return res @classmethod def parse_dict(cls: Type[T_Tlv], data: bytes) -> Dict[int, bytes]: return dict((tlv.tag, tlv.value) for tlv in cls.parse_list(data)) @classmethod def unpack(cls: Type[T_Tlv], tag: int, data: bytes) -> bytes: tlv = cls(data) if tlv.tag != tag: raise ValueError(f"Wrong tag, got 0x{tlv.tag:02x} expected 0x{tag:02x}") return tlv.value
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/core/__init__.py
__init__.py
from . import ( Version, TRANSPORT, USB_INTERFACE, Connection, CommandError, ApplicationNotAvailableError, ) from time import time from enum import Enum, IntEnum, unique from typing import Tuple import abc import struct import logging logger = logging.getLogger(__name__) class ApduError(CommandError): """Thrown when an APDU response has the wrong SW code""" def __init__(self, data: bytes, sw: int): self.data = data self.sw = sw def __str__(self): return f"APDU error: SW=0x{self.sw:04x}" @unique class ApduFormat(str, Enum): """APDU encoding format""" SHORT = "short" EXTENDED = "extended" @unique class AID(bytes, Enum): """YubiKey Application smart card AID values.""" OTP = bytes.fromhex("a0000005272001") MANAGEMENT = bytes.fromhex("a000000527471117") OPENPGP = bytes.fromhex("d27600012401") OATH = bytes.fromhex("a0000005272101") PIV = bytes.fromhex("a000000308") FIDO = bytes.fromhex("a0000006472f0001") HSMAUTH = bytes.fromhex("a000000527210701") @unique class SW(IntEnum): NO_INPUT_DATA = 0x6285 VERIFY_FAIL_NO_RETRY = 0x63C0 WRONG_LENGTH = 0x6700 SECURITY_CONDITION_NOT_SATISFIED = 0x6982 AUTH_METHOD_BLOCKED = 0x6983 DATA_INVALID = 0x6984 CONDITIONS_NOT_SATISFIED = 0x6985 COMMAND_NOT_ALLOWED = 0x6986 INCORRECT_PARAMETERS = 0x6A80 FUNCTION_NOT_SUPPORTED = 0x6A81 FILE_NOT_FOUND = 0x6A82 NO_SPACE = 0x6A84 REFERENCE_DATA_NOT_FOUND = 0x6A88 APPLET_SELECT_FAILED = 0x6999 WRONG_PARAMETERS_P1P2 = 0x6B00 INVALID_INSTRUCTION = 0x6D00 COMMAND_ABORTED = 0x6F00 OK = 0x9000 class SmartCardConnection(Connection, metaclass=abc.ABCMeta): usb_interface = USB_INTERFACE.CCID @property @abc.abstractmethod def transport(self) -> TRANSPORT: """Get the transport type of the connection (USB or NFC)""" @abc.abstractmethod def send_and_receive(self, apdu: bytes) -> Tuple[bytes, int]: """Sends a command APDU and returns the response""" INS_SELECT = 0xA4 P1_SELECT = 0x04 P2_SELECT = 0x00 INS_SEND_REMAINING = 0xC0 SW1_HAS_MORE_DATA = 0x61 SHORT_APDU_MAX_CHUNK = 0xFF def _encode_short_apdu(cla, ins, p1, p2, data, le=0): buf = struct.pack(">BBBBB", cla, ins, p1, p2, len(data)) + data if le: buf += struct.pack(">B", le) return buf def _encode_extended_apdu(cla, ins, p1, p2, data, le=0): buf = struct.pack(">BBBBBH", cla, ins, p1, p2, 0, len(data)) + data if le: buf += struct.pack(">H", le) return buf class SmartCardProtocol: """An implementation of the Smart Card protocol.""" def __init__( self, smartcard_connection: SmartCardConnection, ins_send_remaining: int = INS_SEND_REMAINING, ): self.apdu_format = ApduFormat.SHORT self.connection = smartcard_connection self._ins_send_remaining = ins_send_remaining self._touch_workaround = False self._last_long_resp = 0.0 def close(self) -> None: self.connection.close() def enable_touch_workaround(self, version: Version) -> None: self._touch_workaround = self.connection.transport == TRANSPORT.USB and ( (4, 2, 0) <= version <= (4, 2, 6) ) logger.debug(f"Touch workaround enabled={self._touch_workaround}") def select(self, aid: bytes) -> bytes: """Perform a SELECT instruction. :param aid: The YubiKey application AID value. """ try: return self.send_apdu(0, INS_SELECT, P1_SELECT, P2_SELECT, aid) except ApduError as e: if e.sw in ( SW.FILE_NOT_FOUND, SW.APPLET_SELECT_FAILED, SW.INVALID_INSTRUCTION, SW.WRONG_PARAMETERS_P1P2, ): raise ApplicationNotAvailableError() raise def send_apdu( self, cla: int, ins: int, p1: int, p2: int, data: bytes = b"", le: int = 0 ) -> bytes: """Send APDU message. :param cla: The instruction class. :param ins: The instruction code. :param p1: The instruction parameter. :param p2: The instruction parameter. :param data: The command data in bytes. :param le: The maximum number of bytes in the data field of the response. """ if ( self._touch_workaround and self._last_long_resp > 0 and time() - self._last_long_resp < 2 ): logger.debug("Sending dummy APDU as touch workaround") self.connection.send_and_receive( _encode_short_apdu(0, 0, 0, 0, b"") ) # Dummy APDU, returns error self._last_long_resp = 0 if self.apdu_format is ApduFormat.SHORT: while len(data) > SHORT_APDU_MAX_CHUNK: chunk, data = data[:SHORT_APDU_MAX_CHUNK], data[SHORT_APDU_MAX_CHUNK:] response, sw = self.connection.send_and_receive( _encode_short_apdu(0x10 | cla, ins, p1, p2, chunk, le) ) if sw != SW.OK: raise ApduError(response, sw) response, sw = self.connection.send_and_receive( _encode_short_apdu(cla, ins, p1, p2, data, le) ) get_data = _encode_short_apdu(0, self._ins_send_remaining, 0, 0, b"") elif self.apdu_format is ApduFormat.EXTENDED: response, sw = self.connection.send_and_receive( _encode_extended_apdu(cla, ins, p1, p2, data, le) ) get_data = _encode_extended_apdu(0, self._ins_send_remaining, 0, 0, b"") else: raise TypeError("Invalid ApduFormat set") # Read chained response buf = b"" while sw >> 8 == SW1_HAS_MORE_DATA: buf += response response, sw = self.connection.send_and_receive(get_data) if sw != SW.OK: raise ApduError(response, sw) buf += response if self._touch_workaround and len(buf) > 54: self._last_long_resp = time() else: self._last_long_resp = 0 return buf
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/yubikit/core/smartcard.py
smartcard.py
from yubikit.core import Tlv from cryptography.hazmat.primitives.serialization import pkcs12 from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend from cryptography import x509 from typing import Tuple import ctypes import logging logger = logging.getLogger(__name__) PEM_IDENTIFIER = b"-----BEGIN" class InvalidPasswordError(Exception): """Raised when parsing key/certificate and the password might be wrong/missing.""" def _parse_pkcs12(data, password): try: key, cert, cas = pkcs12.load_key_and_certificates( data, password, default_backend() ) if cert: cas.insert(0, cert) return key, cas except ValueError as e: # cryptography raises ValueError on wrong password raise InvalidPasswordError(e) def parse_private_key(data, password): """Identify, decrypt and return a cryptography private key object. :param data: The private key in bytes. :param password: The password to decrypt the private key (if it is encrypted). """ # PEM if is_pem(data): encrypted = b"ENCRYPTED" in data if encrypted and password is None: raise InvalidPasswordError("No password provided for encrypted key.") try: return serialization.load_pem_private_key( data, password, backend=default_backend() ) except ValueError as e: # Cryptography raises ValueError if decryption fails. if encrypted: raise InvalidPasswordError(e) logger.debug("Failed to parse PEM private key ", exc_info=True) except Exception: logger.debug("Failed to parse PEM private key ", exc_info=True) # PKCS12 if is_pkcs12(data): return _parse_pkcs12(data, password)[0] # DER try: return serialization.load_der_private_key( data, password, backend=default_backend() ) except Exception: logger.debug("Failed to parse private key as DER", exc_info=True) # All parsing failed raise ValueError("Could not parse private key.") def parse_certificates(data, password): """Identify, decrypt and return a list of cryptography x509 certificates. :param data: The certificate(s) in bytes. :param password: The password to decrypt the certificate(s). """ logger.debug("Attempting to parse certificate using PEM, PKCS12 and DER") # PEM if is_pem(data): certs = [] for cert in data.split(PEM_IDENTIFIER): if cert: try: certs.append( x509.load_pem_x509_certificate( PEM_IDENTIFIER + cert, default_backend() ) ) except Exception: logger.debug("Failed to parse PEM certificate", exc_info=True) # Could be valid PEM but not certificates. if not certs: raise ValueError("PEM file does not contain any certificate(s)") return certs # PKCS12 if is_pkcs12(data): return _parse_pkcs12(data, password)[1] # DER try: return [x509.load_der_x509_certificate(data, default_backend())] except Exception: logger.debug("Failed to parse certificate as DER", exc_info=True) raise ValueError("Could not parse certificate.") def get_leaf_certificates(certs): """Extract the leaf certificates from a list of certificates. Leaf certificates are ones whose subject does not appear as issuer among theothers. :param certs: The list of cryptography x509 certificate objects. """ 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 def is_pem(data): return data and PEM_IDENTIFIER in data def is_pkcs12(data): """ Tries to identify a PKCS12 container. The PFX PDU version is assumed to be v3. See: https://tools.ietf.org/html/rfc7292. """ try: header = Tlv.parse_from(Tlv.unpack(0x30, data))[0] return header.tag == 0x02 and header.value == b"\x03" except ValueError: logger.debug("Unable to parse TLV", exc_info=True) return False class OSVERSIONINFOW(ctypes.Structure): _fields_ = [ ("dwOSVersionInfoSize", ctypes.c_ulong), ("dwMajorVersion", ctypes.c_ulong), ("dwMinorVersion", ctypes.c_ulong), ("dwBuildNumber", ctypes.c_ulong), ("dwPlatformId", ctypes.c_ulong), ("szCSDVersion", ctypes.c_wchar * 128), ] def get_windows_version() -> Tuple[int, int, int]: """Get the true Windows version, since sys.getwindowsversion lies.""" osvi = OSVERSIONINFOW() osvi.dwOSVersionInfoSize = ctypes.sizeof(osvi) ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(osvi)) # type: ignore return osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/util.py
util.py
from . import __version__ as ykman_version from .util import get_windows_version from .pcsc import list_readers, list_devices as list_ccid_devices from .hid import list_otp_devices, list_ctap_devices from .piv import get_piv_info from .openpgp import get_openpgp_info from .hsmauth import get_hsmauth_info from yubikit.core.smartcard import SmartCardConnection from yubikit.core.fido import FidoConnection from yubikit.core.otp import OtpConnection from yubikit.management import ManagementSession from yubikit.yubiotp import YubiOtpSession from yubikit.piv import PivSession from yubikit.oath import OathSession from yubikit.openpgp import OpenPgpSession from yubikit.hsmauth import HsmAuthSession from yubikit.support import read_info, get_name from fido2.ctap import CtapError from fido2.ctap2 import Ctap2, ClientPin from dataclasses import asdict from datetime import datetime from typing import List, Dict, Any import platform import ctypes import sys import os def sys_info(): info: Dict[str, Any] = { "ykman": ykman_version, "Python": sys.version, "Platform": sys.platform, "Arch": platform.machine(), "System date": datetime.today().strftime("%Y-%m-%d"), } if sys.platform == "win32": info.update( { "Running as admin": bool(ctypes.windll.shell32.IsUserAnAdmin()), "Windows version": get_windows_version(), } ) else: info["Running as admin"] = os.getuid() == 0 return info def mgmt_info(pid, conn): data: List[Any] = [] try: data.append( { "Raw Info": ManagementSession(conn).backend.read_config(), } ) except Exception as e: data.append(f"Failed to read device info via Management: {e!r}") try: info = read_info(conn, pid) data.append( { "DeviceInfo": asdict(info), "Name": get_name(info, pid.yubikey_type), } ) except Exception as e: data.append(f"Failed to read device info: {e!r}") return data def piv_info(conn): try: piv = PivSession(conn) return get_piv_info(piv) except Exception as e: return f"PIV not accessible {e!r}" def openpgp_info(conn): try: openpgp = OpenPgpSession(conn) return get_openpgp_info(openpgp) except Exception as e: return f"OpenPGP not accessible {e!r}" def oath_info(conn): try: oath = OathSession(conn) return { "Oath version": ".".join("%d" % d for d in oath.version), "Password protected": oath.locked, } except Exception as e: return f"OATH not accessible {e!r}" def hsmauth_info(conn): try: hsmauth = HsmAuthSession(conn) return get_hsmauth_info(hsmauth) except Exception as e: return f"YubiHSM Auth not accessible {e!r}" def ccid_info(): try: readers = {} for reader in list_readers(): try: c = reader.createConnection() c.connect() c.disconnect() result = "Success" except Exception as e: result = f"<{e.__class__.__name__}>" readers[reader.name] = result yubikeys: Dict[str, Any] = {} for dev in list_ccid_devices(): try: with dev.open_connection(SmartCardConnection) as conn: yubikeys[f"{dev!r}"] = { "Management": mgmt_info(dev.pid, conn), "PIV": piv_info(conn), "OATH": oath_info(conn), "OpenPGP": openpgp_info(conn), "YubiHSM Auth": hsmauth_info(conn), } except Exception as e: yubikeys[f"{dev!r}"] = f"PC/SC connection failure: {e!r}" return { "Detected PC/SC readers": readers, "Detected YubiKeys over PC/SC": yubikeys, } except Exception as e: return f"PC/SC failure: {e!r}" def otp_info(): try: yubikeys: Dict[str, Any] = {} for dev in list_otp_devices(): try: dev_info = [] with dev.open_connection(OtpConnection) as conn: dev_info.append( { "Management": mgmt_info(dev.pid, conn), } ) otp = YubiOtpSession(conn) try: config = otp.get_config_state() dev_info.append({"OTP": [f"{config}"]}) except ValueError as e: dev_info.append({"OTP": f"Couldn't read OTP state: {e!r}"}) yubikeys[f"{dev!r}"] = dev_info except Exception as e: yubikeys[f"{dev!r}"] = f"OTP connection failure: {e!r}" return { "Detected YubiKeys over HID OTP": yubikeys, } except Exception as e: return f"HID OTP backend failure: {e!r}" def fido_info(): try: yubikeys: Dict[str, Any] = {} for dev in list_ctap_devices(): try: dev_info: List[Any] = [] with dev.open_connection(FidoConnection) as conn: dev_info.append( { "CTAP device version": "%d.%d.%d" % conn.device_version, "CTAPHID protocol version": conn.version, "Capabilities": conn.capabilities, "Management": mgmt_info(dev.pid, conn), } ) try: ctap2 = Ctap2(conn) ctap_data: Dict[str, Any] = {"Ctap2Info": asdict(ctap2.info)} if ctap2.info.options.get("clientPin"): client_pin = ClientPin(ctap2) ctap_data["PIN retries"] = client_pin.get_pin_retries() bio_enroll = ctap2.info.options.get("bioEnroll") if bio_enroll: ctap_data[ "Fingerprint retries" ] = client_pin.get_uv_retries() elif bio_enroll is False: ctap_data["Fingerprints"] = "Not configured" else: ctap_data["PIN"] = "Not configured" dev_info.append(ctap_data) except (ValueError, CtapError) as e: dev_info.append(f"Couldn't get CTAP2 info: {e!r}") yubikeys[f"{dev!r}"] = dev_info except Exception as e: yubikeys[f"{dev!r}"] = f"FIDO connection failure: {e!r}" return { "Detected YubiKeys over HID FIDO": yubikeys, } except Exception as e: return f"HID FIDO backend failure: {e!r}" def get_diagnostics(): """Runs diagnostics. The result of this can be printed using pretty_print. """ return [ sys_info(), ccid_info(), otp_info(), fido_info(), "End of diagnostics", ]
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/diagnostics.py
diagnostics.py
import time import struct from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SW from fido2.ctap1 import Ctap1, ApduError from typing import Optional U2F_VENDOR_FIRST = 0x40 # FIPS specific INS values INS_FIPS_VERIFY_PIN = U2F_VENDOR_FIRST + 3 INS_FIPS_SET_PIN = U2F_VENDOR_FIRST + 4 INS_FIPS_RESET = U2F_VENDOR_FIRST + 5 INS_FIPS_VERIFY_FIPS_MODE = U2F_VENDOR_FIRST + 6 def is_in_fips_mode(fido_connection: FidoConnection) -> bool: """Check if a YubiKey FIPS is in FIPS approved mode. :param fido_connection: A FIDO connection. """ try: ctap = Ctap1(fido_connection) ctap.send_apdu(ins=INS_FIPS_VERIFY_FIPS_MODE) return True except ApduError as e: # 0x6a81: Function not supported (PIN not set - not FIPS Mode) if e.code == SW.FUNCTION_NOT_SUPPORTED: return False raise def fips_change_pin( fido_connection: FidoConnection, old_pin: Optional[str], new_pin: str ): """Change the PIN on a YubiKey FIPS. If no PIN is set, pass None or an empty string as old_pin. :param fido_connection: A FIDO connection. :param old_pin: The old PIN. :param new_pin: The new PIN. """ ctap = Ctap1(fido_connection) old_pin_bytes = old_pin.encode() if old_pin else b"" new_pin_bytes = new_pin.encode() new_length = len(new_pin_bytes) data = struct.pack("B", new_length) + old_pin_bytes + new_pin_bytes ctap.send_apdu(ins=INS_FIPS_SET_PIN, data=data) def fips_verify_pin(fido_connection: FidoConnection, pin: str): """Unlock the YubiKey FIPS U2F module for credential creation. :param fido_connection: A FIDO connection. :param pin: The FIDO PIN. """ ctap = Ctap1(fido_connection) ctap.send_apdu(ins=INS_FIPS_VERIFY_PIN, data=pin.encode()) def fips_reset(fido_connection: FidoConnection): """Reset the FIDO module of a YubiKey FIPS. Note: This action is only permitted immediately after YubiKey FIPS power-up. It also requires the user to touch the flashing button on the YubiKey, and will halt until that happens, or the command times out. :param fido_connection: A FIDO connection. """ ctap = Ctap1(fido_connection) while True: try: ctap.send_apdu(ins=INS_FIPS_RESET) return except ApduError as e: if e.code == SW.CONDITIONS_NOT_SATISFIED: time.sleep(0.5) else: raise e
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/fido.py
fido.py
import os import json import keyring from pathlib import Path from cryptography.fernet import Fernet, InvalidToken XDG_DATA_HOME = os.environ.get("XDG_DATA_HOME", "~/.local/share") + "/ykman" XDG_CONFIG_HOME = os.environ.get("XDG_CONFIG_HOME", "~/.config") + "/ykman" KEYRING_SERVICE = os.environ.get("YKMAN_KEYRING_SERVICE", "ykman") KEYRING_KEY = os.environ.get("YKMAN_KEYRING_KEY", "wrap_key") class Settings(dict): _config_dir = XDG_CONFIG_HOME def __init__(self, name): self.fname = Path(self._config_dir).expanduser().resolve() / (name + ".json") if self.fname.is_file(): with self.fname.open("r") as fd: self.update(json.load(fd)) def __eq__(self, other): return other is not None and self.fname == other.fname def __ne__(self, other): return other is None or self.fname != other.fname def write(self): conf_dir = self.fname.parent if not conf_dir.is_dir(): conf_dir.mkdir(0o700, parents=True) with self.fname.open("w") as fd: json.dump(self, fd, indent=2) __hash__ = None class Configuration(Settings): _config_dir = XDG_CONFIG_HOME class KeystoreError(Exception): """Error accessing the OS keystore""" class UnwrapValueError(Exception): """Error unwrapping a particular secret value""" class AppData(Settings): _config_dir = XDG_DATA_HOME def __init__(self, name, keyring_service=KEYRING_SERVICE, keyring_key=KEYRING_KEY): super().__init__(name) self._service = keyring_service self._username = keyring_key @property def keyring_unlocked(self) -> bool: return hasattr(self, "_fernet") def ensure_unlocked(self): if not self.keyring_unlocked: try: wrap_key = keyring.get_password(self._service, self._username) except keyring.errors.KeyringError: raise KeystoreError("Keyring locked or unavailable") if wrap_key is None: key = Fernet.generate_key() keyring.set_password(self._service, self._username, key.decode()) self._fernet = Fernet(key) else: self._fernet = Fernet(wrap_key) def get_secret(self, key: str): self.ensure_unlocked() try: return json.loads(self._fernet.decrypt(self[key].encode())) except InvalidToken: raise UnwrapValueError("Undecryptable value") def put_secret(self, key: str, value) -> None: self.ensure_unlocked() self[key] = self._fernet.encrypt(json.dumps(value).encode()).decode()
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/settings.py
settings.py
from . import __version__ from .scancodes import KEYBOARD_LAYOUT from yubikit.core.otp import modhex_encode from yubikit.yubiotp import YubiOtpSession from yubikit.oath import parse_b32_key from enum import Enum from http.client import HTTPSConnection from datetime import datetime from typing import Iterable, Optional import json import struct import random import logging logger = logging.getLogger(__name__) _UPLOAD_HOST = "upload.yubico.com" _UPLOAD_PATH = "/prepare" class _PrepareUploadError(Enum): # Defined here CONNECTION_FAILED = "Failed to open HTTPS connection." NOT_FOUND = "Upload request not recognized by server." SERVICE_UNAVAILABLE = ( "Service temporarily unavailable, please try again later." # noqa: E501 ) # Defined in upload project PRIVATE_ID_INVALID_LENGTH = "Private ID must be 12 characters long." PRIVATE_ID_NOT_HEX = ( "Private ID must consist only of hex characters (0-9A-F)." # noqa: E501 ) PRIVATE_ID_UNDEFINED = "Private ID is required." PUBLIC_ID_INVALID_LENGTH = "Public ID must be 12 characters long." PUBLIC_ID_NOT_MODHEX = "Public ID must consist only of modhex characters (cbdefghijklnrtuv)." # noqa: E501 PUBLIC_ID_NOT_VV = 'Public ID must begin with "vv".' PUBLIC_ID_OCCUPIED = "Public ID is already in use." PUBLIC_ID_UNDEFINED = "Public ID is required." SECRET_KEY_INVALID_LENGTH = "Secret key must be 32 character long." # nosec SECRET_KEY_NOT_HEX = ( "Secret key must consist only of hex characters (0-9A-F)." # noqa: E501 # nosec ) SECRET_KEY_UNDEFINED = "Secret key is required." # nosec SERIAL_NOT_INT = "Serial number must be an integer." SERIAL_TOO_LONG = "Serial number is too long." def message(self): return self.value class _PrepareUploadFailed(Exception): def __init__(self, status, content, error_ids): super().__init__(f"Upload to YubiCloud failed with status {status}: {content}") self.status = status self.content = content self.errors = [ e if isinstance(e, _PrepareUploadError) else _PrepareUploadError[e] for e in error_ids ] def messages(self): return [e.message() for e in self.errors] def _prepare_upload_key( key, public_id, private_id, serial=None, user_agent="python-yubikey-manager/" + __version__, ): modhex_public_id = modhex_encode(public_id) data = { "aes_key": key.hex(), "serial": serial or 0, "public_id": modhex_public_id, "private_id": private_id.hex(), } httpconn = HTTPSConnection(_UPLOAD_HOST, timeout=1) # nosec try: httpconn.request( "POST", _UPLOAD_PATH, body=json.dumps(data, indent=False, sort_keys=True).encode("utf-8"), headers={"Content-Type": "application/json", "User-Agent": user_agent}, ) except Exception: logger.error("Failed to connect to %s", _UPLOAD_HOST, exc_info=True) raise _PrepareUploadFailed(None, None, [_PrepareUploadError.CONNECTION_FAILED]) resp = httpconn.getresponse() if resp.status == 200: url = json.loads(resp.read().decode("utf-8"))["finish_url"] return url else: resp_body = resp.read() logger.debug("Upload failed with status %d: %s", resp.status, resp_body) if resp.status == 404: raise _PrepareUploadFailed( resp.status, resp_body, [_PrepareUploadError.NOT_FOUND] ) elif resp.status == 503: raise _PrepareUploadFailed( resp.status, resp_body, [_PrepareUploadError.SERVICE_UNAVAILABLE] ) else: try: errors = json.loads(resp_body.decode("utf-8")).get("errors") except Exception: errors = [] raise _PrepareUploadFailed(resp.status, resp_body, errors) def is_in_fips_mode(session: YubiOtpSession) -> bool: """Check if the OTP application of a FIPS YubiKey is in FIPS approved mode. :param session: The YubiOTP session. """ return session.backend.send_and_receive(0x14, b"", 1) == b"\1" # type: ignore DEFAULT_PW_CHAR_BLOCKLIST = ["\t", "\n", " "] def generate_static_pw( length: int, keyboard_layout: KEYBOARD_LAYOUT = KEYBOARD_LAYOUT.MODHEX, blocklist: Iterable[str] = DEFAULT_PW_CHAR_BLOCKLIST, ) -> str: """Generate a random password. :param length: The length of the password. :param keyboard_layout: The keyboard layout. :param blocklist: The list of characters to block. """ chars = [k for k in keyboard_layout.value.keys() if k not in blocklist] sr = random.SystemRandom() return "".join([sr.choice(chars) for _ in range(length)]) def parse_oath_key(val: str) -> bytes: """Parse a secret key encoded as either Hex or Base32. :param val: The secret key. """ try: return bytes.fromhex(val) except ValueError: return parse_b32_key(val) def format_oath_code(response: bytes, digits: int = 6) -> str: """Format an OATH code from a hash response. :param response: The response. :param digits: The number of digits in the OATH code. """ offs = response[-1] & 0xF code = struct.unpack_from(">I", response[offs:])[0] & 0x7FFFFFFF return ("%%0%dd" % digits) % (code % 10**digits) def time_challenge(timestamp: int, period: int = 30) -> bytes: """Format a HMAC-SHA1 challenge based on an OATH timestamp and period. :param timestamp: The timestamp. :param period: The period. """ return struct.pack(">q", int(timestamp // period)) def format_csv( serial: int, public_id: bytes, private_id: bytes, key: bytes, access_code: Optional[bytes] = None, timestamp: Optional[datetime] = None, ) -> str: """Produce a CSV line in the "Yubico" format. :param serial: The serial number. :param public_id: The public ID. :param private_id: The private ID. :param key: The secret key. :param access_code: The access code. """ ts = timestamp or datetime.now() return ",".join( [ str(serial), modhex_encode(public_id), private_id.hex(), key.hex(), access_code.hex() if access_code else "", ts.isoformat(timespec="seconds"), "", # Add trailing comma ] )
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/otp.py
otp.py
from .base import YkmanDevice from .device import list_all_devices, scan_devices from .pcsc import list_devices as list_ccid from yubikit.core import TRANSPORT from yubikit.core.otp import OtpConnection from yubikit.core.smartcard import SmartCardConnection from yubikit.core.fido import FidoConnection from yubikit.management import DeviceInfo from yubikit.support import get_name, read_info from smartcard.Exceptions import NoCardException, CardConnectionException from time import sleep from typing import Generator, Optional, Set """ Various helpers intended to simplify scripting. Add an import to your script: from ykman import scripting as s Example usage: yubikey = s.single() print("Here is a YubiKey:", yubikey) print("Insert multiple YubiKeys") for yubikey in s.multi(): print("You inserted {yubikey}") print("You pressed Ctrl+C, end of script") """ class ScriptingDevice: """Scripting-friendly proxy for YkmanDevice. This wrapper adds some helpful utility methods useful for scripting. """ def __init__(self, wrapped, info): self._wrapped = wrapped self._info = info self._name = get_name(info, self.pid.yubikey_type if self.pid else None) def __getattr__(self, attr): return getattr(self._wrapped, attr) def __str__(self): serial = self._info.serial return f"{self._name} ({serial})" if serial else self._name @property def info(self) -> DeviceInfo: return self._info @property def name(self) -> str: return self._name def otp(self) -> OtpConnection: """Establish a OTP connection.""" return self.open_connection(OtpConnection) def smart_card(self) -> SmartCardConnection: """Establish a Smart Card connection.""" return self.open_connection(SmartCardConnection) def fido(self) -> FidoConnection: """Establish a FIDO connection.""" return self.open_connection(FidoConnection) YkmanDevice.register(ScriptingDevice) def single(*, prompt=True) -> ScriptingDevice: """Connect to a YubiKey. :param prompt: When set, you will be prompted to insert a YubiKey. """ pids, state = scan_devices() n_devs = sum(pids.values()) if prompt and n_devs == 0: print("Insert YubiKey...") while n_devs == 0: sleep(1.0) pids, new_state = scan_devices() n_devs = sum(pids.values()) devs = list_all_devices() if len(devs) == 1: return ScriptingDevice(*devs[0]) raise ValueError("Failed to get single YubiKey") def multi( *, ignore_duplicates: bool = True, allow_initial: bool = False, prompt: bool = True ) -> Generator[ScriptingDevice, None, None]: """Connect to multiple YubiKeys. :param ignore_duplicates: When set, duplicates are ignored. :param allow_initial: When set, YubiKeys can be connected at the start of the function call. :param prompt: When set, you will be prompted to insert a YubiKey. """ state = None handled_serials: Set[Optional[int]] = set() pids, _ = scan_devices() n_devs = sum(pids.values()) if n_devs == 0: if prompt: print("Insert YubiKeys, one at a time...") elif not allow_initial: raise ValueError("YubiKeys must not be present initially.") while True: # Run this until we stop the script with Ctrl+C pids, new_state = scan_devices() if new_state != state: state = new_state # State has changed serials = set() if len(pids) == 0 and None in handled_serials: handled_serials.remove(None) # Allow one key without serial at a time for device, info in list_all_devices(): serials.add(info.serial) if info.serial not in handled_serials: handled_serials.add(info.serial) yield ScriptingDevice(device, info) if not ignore_duplicates: # Reset handled serials to currently connected handled_serials = serials else: try: sleep(1.0) # No change, sleep for 1 second. except KeyboardInterrupt: return # Stop waiting def _get_reader(reader) -> YkmanDevice: readers = [d for d in list_ccid(reader) if d.transport == TRANSPORT.NFC] if not readers: raise ValueError(f"No NFC reader found matching filter: '{reader}'") elif len(readers) > 1: names = [r.fingerprint for r in readers] raise ValueError(f"Multiple NFC readers matching filter: '{reader}' {names}") return readers[0] def single_nfc(reader="", *, prompt=True) -> ScriptingDevice: """Connect to a YubiKey over NFC. :param reader: The name of the NFC reader. :param prompt: When set, you will prompted to place a YubiKey on NFC reader. """ device = _get_reader(reader) while True: try: with device.open_connection(SmartCardConnection) as connection: info = read_info(connection) return ScriptingDevice(device, info) except NoCardException: if prompt: print("Place YubiKey on NFC reader...") prompt = False sleep(1.0) def multi_nfc( reader="", *, ignore_duplicates=True, allow_initial=False, prompt=True ) -> Generator[ScriptingDevice, None, None]: """Connect to multiple YubiKeys over NFC. :param reader: The name of the NFC reader. :param ignore_duplicates: When set, duplicates are ignored. :param allow_initial: When set, YubiKeys can be connected at the start of the function call. :param prompt: When set, you will be prompted to place YubiKeys on the NFC reader. """ device = _get_reader(reader) prompted = False try: with device.open_connection(SmartCardConnection) as connection: if not allow_initial: raise ValueError("YubiKey must not be present initially.") except NoCardException: if prompt: print("Place YubiKey on NFC reader...") prompted = True sleep(1.0) handled_serials: Set[Optional[int]] = set() current: Optional[int] = -1 while True: # Run this until we stop the script with Ctrl+C try: with device.open_connection(SmartCardConnection) as connection: info = read_info(connection) if info.serial in handled_serials or current == info.serial: if prompt and not prompted: print("Remove YubiKey from NFC reader.") prompted = True else: current = info.serial if ignore_duplicates: handled_serials.add(current) yield ScriptingDevice(device, info) prompted = False except NoCardException: if None in handled_serials: handled_serials.remove(None) # Allow one key without serial at a time current = -1 if prompt and not prompted: print("Place YubiKey on NFC reader...") prompted = True except CardConnectionException: pass try: sleep(1.0) # No change, sleep for 1 second. except KeyboardInterrupt: return # Stop waiting
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scripting.py
scripting.py
from yubikit.core import Connection, PID, TRANSPORT, YUBIKEY from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from yubikit.management import ( DeviceInfo, USB_INTERFACE, ) from yubikit.support import read_info from .base import YkmanDevice from .hid import ( list_otp_devices as _list_otp_devices, list_ctap_devices as _list_ctap_devices, ) from .pcsc import list_devices as _list_ccid_devices from smartcard.pcsc.PCSCExceptions import EstablishContextException from smartcard.Exceptions import NoCardException from time import sleep, time from collections import Counter from typing import ( Dict, Mapping, List, Tuple, Iterable, Type, Hashable, Set, ) import sys import ctypes import logging logger = logging.getLogger(__name__) def _warn_once(message, e_type=Exception): warned: List[bool] = [] def outer(f): def inner(): try: return f() except e_type: if not warned: logger.warning(message) warned.append(True) raise return inner return outer @_warn_once( "PC/SC not available. Smart card (CCID) protocols will not function.", EstablishContextException, ) def list_ccid_devices(): """List CCID devices.""" return _list_ccid_devices() @_warn_once("No CTAP HID backend available. FIDO protocols will not function.") def list_ctap_devices(): """List CTAP devices.""" return _list_ctap_devices() @_warn_once("No OTP HID backend available. OTP protocols will not function.") def list_otp_devices(): """List OTP devices.""" return _list_otp_devices() _CONNECTION_LIST_MAPPING = { SmartCardConnection: list_ccid_devices, OtpConnection: list_otp_devices, FidoConnection: list_ctap_devices, } def scan_devices() -> Tuple[Mapping[PID, int], int]: """Scan USB for attached YubiKeys, without opening any connections. :return: A dict mapping PID to device count, and a state object which can be used to detect changes in attached devices. """ fingerprints = set() merged: Dict[PID, int] = {} for list_devs in _CONNECTION_LIST_MAPPING.values(): try: devs = list_devs() except Exception: logger.debug("Device listing error", exc_info=True) devs = [] merged.update(Counter(d.pid for d in devs if d.pid is not None)) fingerprints.update({d.fingerprint for d in devs}) if sys.platform == "win32" and not bool(ctypes.windll.shell32.IsUserAnAdmin()): from .hid.windows import list_paths counter: Counter[PID] = Counter() for pid, path in list_paths(): if pid not in merged: try: counter[PID(pid)] += 1 fingerprints.add(path) except ValueError: # Unsupported PID logger.debug(f"Unsupported Yubico device with PID: {pid:02x}") merged.update(counter) return merged, hash(tuple(fingerprints)) class _PidGroup: def __init__(self, pid): self._pid = pid self._infos: Dict[Hashable, DeviceInfo] = {} self._resolved: Dict[Hashable, Dict[USB_INTERFACE, YkmanDevice]] = {} self._unresolved: Dict[USB_INTERFACE, List[YkmanDevice]] = {} self._devcount: Dict[USB_INTERFACE, int] = Counter() self._fingerprints: Set[Hashable] = set() self._ctime = time() def _key(self, info): return ( info.serial, info.version, info.form_factor, str(info.supported_capabilities), info.config.get_bytes(False), info.is_locked, info.is_fips, info.is_sky, ) def add(self, conn_type, dev, force_resolve=False): logger.debug(f"Add device for {conn_type}: {dev}") iface = conn_type.usb_interface self._fingerprints.add(dev.fingerprint) self._devcount[iface] += 1 if force_resolve or len(self._resolved) < max(self._devcount.values()): try: with dev.open_connection(conn_type) as conn: info = read_info(conn, dev.pid) key = self._key(info) self._infos[key] = info self._resolved.setdefault(key, {})[iface] = dev logger.debug(f"Resolved device {info.serial}") return except Exception: logger.warning("Failed opening device", exc_info=True) self._unresolved.setdefault(iface, []).append(dev) def supports_connection(self, conn_type): return conn_type.usb_interface in self._devcount def connect(self, key, conn_type): iface = conn_type.usb_interface resolved = self._resolved[key].get(iface) if resolved: return resolved.open_connection(conn_type) devs = self._unresolved.get(iface, []) failed = [] try: while devs: dev = devs.pop() try: conn = dev.open_connection(conn_type) info = read_info(conn, dev.pid) dev_key = self._key(info) if dev_key in self._infos: self._resolved.setdefault(dev_key, {})[iface] = dev logger.debug(f"Resolved device {info.serial}") if dev_key == key: return conn elif self._pid.yubikey_type == YUBIKEY.NEO and not devs: self._resolved.setdefault(key, {})[iface] = dev logger.debug("Resolved last NEO device without serial") return conn conn.close() except Exception: logger.warning("Failed opening device", exc_info=True) failed.append(dev) finally: devs.extend(failed) if self._devcount[iface] < len(self._infos): logger.debug(f"Checking for more devices over {iface!s}") for dev in _CONNECTION_LIST_MAPPING[conn_type](): if self._pid == dev.pid and dev.fingerprint not in self._fingerprints: self.add(conn_type, dev, True) resolved = self._resolved[key].get(iface) if resolved: return resolved.open_connection(conn_type) # Retry if we are within a 5 second period after creation, # as not all USB interface become usable at the exact same time. if time() < self._ctime + 5: logger.debug("Device not found, retry in 1s") sleep(1.0) return self.connect(key, conn_type) raise ValueError("Failed to connect to the device") def get_devices(self): results = [] for key, info in self._infos.items(): dev = next(iter(self._resolved[key].values())) results.append( (_UsbCompositeDevice(self, key, dev.fingerprint, dev.pid), info) ) return results class _UsbCompositeDevice(YkmanDevice): def __init__(self, group, key, fingerprint, pid): super().__init__(TRANSPORT.USB, fingerprint, pid) self._group = group self._key = key def supports_connection(self, connection_type): return self._group.supports_connection(connection_type) def open_connection(self, connection_type): if not self.supports_connection(connection_type): raise ValueError("Unsupported Connection type") # Allow for ~3s reclaim time on NEO for CCID assert self.pid # nosec if self.pid.yubikey_type == YUBIKEY.NEO and issubclass( connection_type, SmartCardConnection ): for _ in range(6): try: return self._group.connect(self._key, connection_type) except (NoCardException, ValueError): sleep(0.5) return self._group.connect(self._key, connection_type) def list_all_devices( connection_types: Iterable[Type[Connection]] = _CONNECTION_LIST_MAPPING.keys(), ) -> List[Tuple[YkmanDevice, DeviceInfo]]: """Connect to all attached YubiKeys and read device info from them. :param connection_types: An iterable of YubiKey connection types. :return: A list of (device, info) tuples for each connected device. """ groups: Dict[PID, _PidGroup] = {} for connection_type in connection_types: for base_type in _CONNECTION_LIST_MAPPING: if issubclass(connection_type, base_type): connection_type = base_type break else: raise ValueError("Invalid connection type") try: for dev in _CONNECTION_LIST_MAPPING[connection_type](): group = groups.setdefault(dev.pid, _PidGroup(dev.pid)) group.add(connection_type, dev) except Exception: logger.exception("Unable to list devices for connection") devices = [] for group in groups.values(): devices.extend(group.get_devices()) return devices
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/device.py
device.py
from yubikit.core import Tlv, BadResponseError, NotSupportedError from yubikit.core.smartcard import ApduError, SW from yubikit.piv import ( PivSession, SLOT, OBJECT_ID, KEY_TYPE, MANAGEMENT_KEY_TYPE, ALGORITHM, TAG_LRC, ) from cryptography import x509 from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa, ec, padding from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.backends import default_backend from cryptography.x509.oid import NameOID from collections import OrderedDict from datetime import datetime import logging import struct import os import re from typing import Union, Mapping, Optional, List, Dict, Type, Any, cast logger = logging.getLogger(__name__) OBJECT_ID_PIVMAN_DATA = 0x5FFF00 OBJECT_ID_PIVMAN_PROTECTED_DATA = OBJECT_ID.PRINTED # Use slot for printed information. _NAME_ATTRIBUTES = { "CN": NameOID.COMMON_NAME, "L": NameOID.LOCALITY_NAME, "ST": NameOID.STATE_OR_PROVINCE_NAME, "O": NameOID.ORGANIZATION_NAME, "OU": NameOID.ORGANIZATIONAL_UNIT_NAME, "C": NameOID.COUNTRY_NAME, "STREET": NameOID.STREET_ADDRESS, "DC": NameOID.DOMAIN_COMPONENT, "UID": NameOID.USER_ID, } _ESCAPED = "\\\"+,'<> #=" def _parse(value: str) -> List[List[str]]: remaining = list(value) name = [] entry = [] buf = "" hexbuf = b"" while remaining: c = remaining.pop(0) if c == "\\": c1 = remaining.pop(0) if c1 in _ESCAPED: c = c1 else: c2 = remaining.pop(0) hexbuf += bytes.fromhex(c1 + c2) try: c = hexbuf.decode() hexbuf = b"" except UnicodeDecodeError: continue # Possibly multi-byte, expect more hex elif c in ",+": entry.append(buf) buf = "" if c == ",": name.append(entry) entry = [] continue if hexbuf: raise ValueError("Invalid UTF-8 data") buf += c entry.append(buf) name.append(entry) return name _DOTTED_STRING_RE = re.compile(r"\d(\.\d+)+") def parse_rfc4514_string(value: str) -> x509.Name: """Parse an RFC 4514 string into a x509.Name. See: https://tools.ietf.org/html/rfc4514.html :param value: An RFC 4514 string. """ name = _parse(value) attributes: List[x509.RelativeDistinguishedName] = [] for entry in name: parts = [] for part in entry: if "=" not in part: raise ValueError("Invalid RFC 4514 string") k, v = part.split("=", 1) if k in _NAME_ATTRIBUTES: attr = _NAME_ATTRIBUTES[k] elif _DOTTED_STRING_RE.fullmatch(k): attr = x509.ObjectIdentifier(k) else: raise ValueError(f"Unsupported attribute: '{k}'") parts.append(x509.NameAttribute(attr, v)) attributes.insert(0, x509.RelativeDistinguishedName(parts)) return x509.Name(attributes) def _dummy_key(algorithm): if algorithm == KEY_TYPE.RSA1024: return rsa.generate_private_key(65537, 1024, default_backend()) # nosec if algorithm == KEY_TYPE.RSA2048: return rsa.generate_private_key(65537, 2048, default_backend()) if algorithm == KEY_TYPE.ECCP256: return ec.generate_private_key(ec.SECP256R1(), default_backend()) if algorithm == KEY_TYPE.ECCP384: return ec.generate_private_key(ec.SECP384R1(), default_backend()) raise ValueError("Invalid algorithm") def derive_management_key(pin: str, salt: bytes) -> bytes: """Derive a management key from the users PIN and a salt. NOTE: This method of derivation is deprecated! Protect the management key using PivmanProtectedData instead. :param pin: The PIN. :param salt: The salt. """ kdf = PBKDF2HMAC(hashes.SHA1(), 24, salt, 10000, default_backend()) # nosec return kdf.derive(pin.encode("utf-8")) def generate_random_management_key(algorithm: MANAGEMENT_KEY_TYPE) -> bytes: """Generate a new random management key. :param algorithm: The algorithm for the management key. """ return os.urandom(algorithm.key_len) class PivmanData: def __init__(self, raw_data: bytes = Tlv(0x80)): data = Tlv.parse_dict(Tlv(raw_data).value) self._flags = struct.unpack(">B", data[0x81])[0] if 0x81 in data else None self.salt = data.get(0x82) self.pin_timestamp = struct.unpack(">I", data[0x83]) if 0x83 in data else None def _get_flag(self, mask: int) -> bool: return bool((self._flags or 0) & mask) def _set_flag(self, mask: int, value: bool) -> None: if value: self._flags = (self._flags or 0) | mask elif self._flags is not None: self._flags &= ~mask @property def puk_blocked(self) -> bool: return self._get_flag(0x01) @puk_blocked.setter def puk_blocked(self, value: bool) -> None: self._set_flag(0x01, value) @property def mgm_key_protected(self) -> bool: return self._get_flag(0x02) @mgm_key_protected.setter def mgm_key_protected(self, value: bool) -> None: self._set_flag(0x02, value) @property def has_protected_key(self) -> bool: return self.has_derived_key or self.has_stored_key @property def has_derived_key(self) -> bool: return self.salt is not None @property def has_stored_key(self) -> bool: return self.mgm_key_protected def get_bytes(self) -> bytes: data = b"" if self._flags is not None: data += Tlv(0x81, struct.pack(">B", self._flags)) if self.salt is not None: data += Tlv(0x82, self.salt) if self.pin_timestamp is not None: data += Tlv(0x83, struct.pack(">I", self.pin_timestamp)) return Tlv(0x80, data) class PivmanProtectedData: def __init__(self, raw_data: bytes = Tlv(0x88)): data = Tlv.parse_dict(Tlv(raw_data).value) self.key = data.get(0x89) def get_bytes(self) -> bytes: data = b"" if self.key is not None: data += Tlv(0x89, self.key) return Tlv(0x88, data) def get_pivman_data(session: PivSession) -> PivmanData: """Read out the Pivman data from a YubiKey. :param session: The PIV session. """ logger.debug("Reading pivman data") try: return PivmanData(session.get_object(OBJECT_ID_PIVMAN_DATA)) except ApduError as e: if e.sw == SW.FILE_NOT_FOUND: # No data there, initialise a new object. logger.debug("No data, initializing blank") return PivmanData() raise def get_pivman_protected_data(session: PivSession) -> PivmanProtectedData: """Read out the Pivman protected data from a YubiKey. This function requires PIN verification prior to being called. :param session: The PIV session. """ logger.debug("Reading protected pivman data") try: return PivmanProtectedData(session.get_object(OBJECT_ID_PIVMAN_PROTECTED_DATA)) except ApduError as e: if e.sw == SW.FILE_NOT_FOUND: # No data there, initialise a new object. logger.debug("No data, initializing blank") return PivmanProtectedData() raise def pivman_set_mgm_key( session: PivSession, new_key: bytes, algorithm: MANAGEMENT_KEY_TYPE, touch: bool = False, store_on_device: bool = False, ) -> None: """Set a new management key, while keeping PivmanData in sync. :param session: The PIV session. :param new_key: The new management key. :param algorithm: The algorithm for the management key. :param touch: If set, touch is required. :param store_on_device: If set, the management key is stored on device. """ pivman = get_pivman_data(session) pivman_prot = None if store_on_device or (not store_on_device and pivman.has_stored_key): # Ensure we have access to protected data before overwriting key try: pivman_prot = get_pivman_protected_data(session) except Exception: logger.debug("Failed to initialize protected pivman data", exc_info=True) if store_on_device: raise # Set the new management key session.set_management_key(algorithm, new_key, touch) if pivman.has_derived_key: # Clear salt for old derived keys. logger.debug("Clearing salt in pivman data") pivman.salt = None # Set flag for stored or not stored key. pivman.mgm_key_protected = store_on_device # Update readable pivman data session.put_object(OBJECT_ID_PIVMAN_DATA, pivman.get_bytes()) if pivman_prot is not None: if store_on_device: # Store key in protected pivman data logger.debug("Storing key in protected pivman data") pivman_prot.key = new_key session.put_object(OBJECT_ID_PIVMAN_PROTECTED_DATA, pivman_prot.get_bytes()) elif pivman_prot.key: # If new key should not be stored and there is an old stored key, # try to clear it. logger.debug("Clearing old key in protected pivman data") try: pivman_prot.key = None session.put_object( OBJECT_ID_PIVMAN_PROTECTED_DATA, pivman_prot.get_bytes(), ) except ApduError: logger.debug("No PIN provided, can't clear key...", exc_info=True) def pivman_change_pin(session: PivSession, old_pin: str, new_pin: str) -> None: """Change the PIN, while keeping PivmanData in sync. :param session: The PIV session. :param old_pin: The old PIN. :param new_pin: The new PIN. """ session.change_pin(old_pin, new_pin) pivman = get_pivman_data(session) if pivman.has_derived_key: logger.debug("Has derived management key, update for new PIN") session.authenticate( MANAGEMENT_KEY_TYPE.TDES, derive_management_key(old_pin, cast(bytes, pivman.salt)), ) session.verify_pin(new_pin) new_salt = os.urandom(16) new_key = derive_management_key(new_pin, new_salt) session.set_management_key(MANAGEMENT_KEY_TYPE.TDES, new_key) pivman.salt = new_salt session.put_object(OBJECT_ID_PIVMAN_DATA, pivman.get_bytes()) def list_certificates(session: PivSession) -> Mapping[SLOT, Optional[x509.Certificate]]: """Read out and parse stored certificates. Only certificates which are successfully parsed are returned. :param session: The PIV session. """ certs = OrderedDict() for slot in set(SLOT) - {SLOT.ATTESTATION}: try: certs[slot] = session.get_certificate(slot) except ApduError: pass except BadResponseError: certs[slot] = None # type: ignore return certs def check_key( session: PivSession, slot: SLOT, public_key: Union[rsa.RSAPublicKey, ec.EllipticCurvePublicKey], ) -> bool: """Check that a given public key corresponds to the private key in a slot. This will create a signature using the private key, so the PIN must be verified prior to calling this function if the PIN policy requires it. :param session: The PIV session. :param slot: The slot. :param public_key: The public key. """ try: test_data = b"test" logger.debug( "Testing private key by creating a test signature, and verifying it" ) test_sig = session.sign( slot, KEY_TYPE.from_public_key(public_key), test_data, hashes.SHA256(), padding.PKCS1v15(), # Only used for RSA ) if isinstance(public_key, rsa.RSAPublicKey): public_key.verify( test_sig, test_data, padding.PKCS1v15(), hashes.SHA256(), ) elif isinstance(public_key, ec.EllipticCurvePublicKey): public_key.verify(test_sig, test_data, ec.ECDSA(hashes.SHA256())) else: raise ValueError("Unknown key type: " + type(public_key)) return True except ApduError as e: if e.sw in (SW.INCORRECT_PARAMETERS, SW.WRONG_PARAMETERS_P1P2): logger.debug(f"Couldn't create signature: SW={e.sw:04x}") return False raise except InvalidSignature: logger.debug("Signature verification failed") return False def generate_chuid() -> bytes: """Generate a CHUID (Cardholder Unique Identifier).""" # Non-Federal Issuer FASC-N # [9999-9999-999999-0-1-0000000000300001] FASC_N = ( b"\xd4\xe7\x39\xda\x73\x9c\xed\x39\xce\x73\x9d\x83\x68" + b"\x58\x21\x08\x42\x10\x84\x21\xc8\x42\x10\xc3\xeb" ) # Expires on: 2030-01-01 EXPIRY = b"\x32\x30\x33\x30\x30\x31\x30\x31" return ( Tlv(0x30, FASC_N) + Tlv(0x34, os.urandom(16)) + Tlv(0x35, EXPIRY) + Tlv(0x3E) + Tlv(TAG_LRC) ) def generate_ccc() -> bytes: """Generate a CCC (Card Capability Container).""" return ( Tlv(0xF0, b"\xa0\x00\x00\x01\x16\xff\x02" + os.urandom(14)) + Tlv(0xF1, b"\x21") + Tlv(0xF2, b"\x21") + Tlv(0xF3) + Tlv(0xF4, b"\x00") + Tlv(0xF5, b"\x10") + Tlv(0xF6) + Tlv(0xF7) + Tlv(0xFA) + Tlv(0xFB) + Tlv(0xFC) + Tlv(0xFD) + Tlv(TAG_LRC) ) def get_piv_info(session: PivSession): """Get human readable information about the PIV configuration. :param session: The PIV session. """ pivman = get_pivman_data(session) info: Dict[str, Any] = { "PIV version": session.version, } lines: List[Any] = [info] try: pin_data = session.get_pin_metadata() if pin_data.default_value: lines.append("WARNING: Using default PIN!") tries_str = "%d/%d" % (pin_data.attempts_remaining, pin_data.total_attempts) except NotSupportedError: # Largest possible number of PIN tries to get back is 15 tries = session.get_pin_attempts() tries_str = "15 or more" if tries == 15 else str(tries) info["PIN tries remaining"] = tries_str if pivman.puk_blocked: lines.append("PUK is blocked") else: try: puk_data = session.get_puk_metadata() if puk_data.default_value: lines.append("WARNING: Using default PUK!") tries_str = "%d/%d" % ( puk_data.attempts_remaining, puk_data.total_attempts, ) info["PUK tries remaining"] = tries_str except NotSupportedError: pass try: metadata = session.get_management_key_metadata() if metadata.default_value: lines.append("WARNING: Using default Management key!") key_type = metadata.key_type except NotSupportedError: key_type = MANAGEMENT_KEY_TYPE.TDES info["Management key algorithm"] = key_type.name if pivman.has_derived_key: lines.append("Management key is derived from PIN.") if pivman.has_stored_key: lines.append("Management key is stored on the YubiKey, protected by PIN.") objects: Dict[str, Any] = {} lines.append(objects) try: objects["CHUID"] = session.get_object(OBJECT_ID.CHUID) except ApduError as e: if e.sw == SW.FILE_NOT_FOUND: objects["CHUID"] = "No data available" try: objects["CCC"] = session.get_object(OBJECT_ID.CAPABILITY) except ApduError as e: if e.sw == SW.FILE_NOT_FOUND: objects["CCC"] = "No data available" for slot, cert in list_certificates(session).items(): cert_data: Dict[str, Any] = {} objects[f"Slot {slot}"] = cert_data if cert: try: # Try to read out full DN, fallback to only CN. # Support for DN was added in crytography 2.5 subject_dn = cert.subject.rfc4514_string() issuer_dn = cert.issuer.rfc4514_string() print_dn = True except AttributeError: print_dn = False logger.debug("Failed to read DN, falling back to only CNs") cn = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) subject_cn = cn[0].value if cn else "None" cn = cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) issuer_cn = cn[0].value if cn else "None" except ValueError as e: # Malformed certificates may throw ValueError logger.debug("Failed parsing certificate", exc_info=True) cert_data["Error"] = f"Malformed certificate: {e}" continue fingerprint = cert.fingerprint(hashes.SHA256()).hex() try: key_algo = KEY_TYPE.from_public_key(cert.public_key()).name except ValueError: key_algo = "Unsupported" serial = cert.serial_number try: not_before: Optional[datetime] = cert.not_valid_before except ValueError: logger.debug("Failed reading not_valid_before", exc_info=True) not_before = None try: not_after: Optional[datetime] = cert.not_valid_after except ValueError: logger.debug("Failed reading not_valid_after", exc_info=True) not_after = None # Print out everything cert_data["Algorithm"] = key_algo if print_dn: cert_data["Subject DN"] = subject_dn cert_data["Issuer DN"] = issuer_dn else: cert_data["Subject CN"] = subject_cn cert_data["Issuer CN"] = issuer_cn cert_data["Serial"] = serial cert_data["Fingerprint"] = fingerprint if not_before: cert_data["Not before"] = not_before.isoformat() if not_after: cert_data["Not after"] = not_after.isoformat() else: cert_data["Error"] = "Failed to parse certificate" return lines _AllowedHashTypes = Union[ hashes.SHA224, hashes.SHA256, hashes.SHA384, hashes.SHA512, hashes.SHA3_224, hashes.SHA3_256, hashes.SHA3_384, hashes.SHA3_512, ] def sign_certificate_builder( session: PivSession, slot: SLOT, key_type: KEY_TYPE, builder: x509.CertificateBuilder, hash_algorithm: Type[_AllowedHashTypes] = hashes.SHA256, ) -> x509.Certificate: """Sign a Certificate. :param session: The PIV session. :param slot: The slot. :param key_type: The key type. :param builder: The x509 certificate builder object. :param hash_algorithm: The hash algorithm. """ logger.debug("Signing a certificate") dummy_key = _dummy_key(key_type) cert = builder.sign(dummy_key, hash_algorithm(), default_backend()) sig = session.sign( slot, key_type, cert.tbs_certificate_bytes, hash_algorithm(), padding.PKCS1v15(), # Only used for RSA ) seq = Tlv.parse_list(Tlv.unpack(0x30, cert.public_bytes(Encoding.DER))) # Replace signature, add unused bits = 0 seq[2] = Tlv(seq[2].tag, b"\0" + sig) # Re-assemble sequence der = Tlv(0x30, b"".join(seq)) return x509.load_der_x509_certificate(der, default_backend()) def sign_csr_builder( session: PivSession, slot: SLOT, public_key: Union[rsa.RSAPublicKey, ec.EllipticCurvePublicKey], builder: x509.CertificateSigningRequestBuilder, hash_algorithm: Type[_AllowedHashTypes] = hashes.SHA256, ) -> x509.CertificateSigningRequest: """Sign a CSR. :param session: The PIV session. :param slot: The slot. :param public_key: The public key. :param builder: The x509 certificate signing request builder object. :param hash_algorithm: The hash algorithm. """ logger.debug("Signing a CSR") key_type = KEY_TYPE.from_public_key(public_key) dummy_key = _dummy_key(key_type) csr = builder.sign(dummy_key, hash_algorithm(), default_backend()) seq = Tlv.parse_list(Tlv.unpack(0x30, csr.public_bytes(Encoding.DER))) # Replace public key pub_format = ( PublicFormat.PKCS1 if key_type.algorithm == ALGORITHM.RSA else PublicFormat.SubjectPublicKeyInfo ) dummy_bytes = dummy_key.public_key().public_bytes(Encoding.DER, pub_format) pub_bytes = public_key.public_bytes(Encoding.DER, pub_format) seq[0] = Tlv(seq[0].replace(dummy_bytes, pub_bytes)) sig = session.sign( slot, key_type, seq[0], hash_algorithm(), padding.PKCS1v15(), # Only used for RSA ) # Replace signature, add unused bits = 0 seq[2] = Tlv(seq[2].tag, b"\0" + sig) # Re-assemble sequence der = Tlv(0x30, b"".join(seq)) return x509.load_der_x509_csr(der, default_backend()) def generate_self_signed_certificate( session: PivSession, slot: SLOT, public_key: Union[rsa.RSAPublicKey, ec.EllipticCurvePublicKey], subject_str: str, valid_from: datetime, valid_to: datetime, hash_algorithm: Type[_AllowedHashTypes] = hashes.SHA256, ) -> x509.Certificate: """Generate a self-signed certificate using a private key in a slot. :param session: The PIV session. :param slot: The slot. :param public_key: The public key. :param subject_str: The subject RFC 4514 string. :param valid_from: The date from when the certificate is valid. :param valid_to: The date when the certificate expires. :param hash_algorithm: The hash algorithm. """ logger.debug("Generating a self-signed certificate") key_type = KEY_TYPE.from_public_key(public_key) subject = parse_rfc4514_string(subject_str) builder = ( x509.CertificateBuilder() .public_key(public_key) .subject_name(subject) .issuer_name(subject) # Same as subject on self-signed certificate. .serial_number(x509.random_serial_number()) .not_valid_before(valid_from) .not_valid_after(valid_to) ) return sign_certificate_builder(session, slot, key_type, builder, hash_algorithm) def generate_csr( session: PivSession, slot: SLOT, public_key: Union[rsa.RSAPublicKey, ec.EllipticCurvePublicKey], subject_str: str, hash_algorithm: Type[_AllowedHashTypes] = hashes.SHA256, ) -> x509.CertificateSigningRequest: """Generate a CSR using a private key in a slot. :param session: The PIV session. :param slot: The slot. :param public_key: The public key. :param subject_str: The subject RFC 4514 string. :param hash_algorithm: The hash algorithm. """ logger.debug("Generating a CSR") builder = x509.CertificateSigningRequestBuilder().subject_name( parse_rfc4514_string(subject_str) ) return sign_csr_builder(session, slot, public_key, builder, hash_algorithm)
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/piv.py
piv.py
from .base import OtpYubiKeyDevice, YUBICO_VID, USAGE_OTP from yubikit.core.otp import OtpConnection from yubikit.logging import LOG_LEVEL import ctypes import ctypes.util import logging logger = logging.getLogger(__name__) # Constants HID_DEVICE_PROPERTY_VENDOR_ID = b"VendorID" HID_DEVICE_PROPERTY_PRODUCT_ID = b"ProductID" HID_DEVICE_PROPERTY_PRODUCT = b"Product" HID_DEVICE_PROPERTY_PRIMARY_USAGE = b"PrimaryUsage" HID_DEVICE_PROPERTY_PRIMARY_USAGE_PAGE = b"PrimaryUsagePage" HID_DEVICE_PROPERTY_MAX_INPUT_REPORT_SIZE = b"MaxInputReportSize" HID_DEVICE_PROPERTY_MAX_OUTPUT_REPORT_SIZE = b"MaxOutputReportSize" HID_DEVICE_PROPERTY_REPORT_ID = b"ReportID" # Declare C types class _CFType(ctypes.Structure): pass class _CFString(_CFType): pass class _CFSet(_CFType): pass class _IOHIDManager(_CFType): pass class _IOHIDDevice(_CFType): pass class _CFAllocator(_CFType): pass CF_SET_REF = ctypes.POINTER(_CFSet) CF_STRING_REF = ctypes.POINTER(_CFString) CF_TYPE_REF = ctypes.POINTER(_CFType) CF_ALLOCATOR_REF = ctypes.POINTER(_CFAllocator) CF_DICTIONARY_REF = ctypes.c_void_p CF_MUTABLE_DICTIONARY_REF = ctypes.c_void_p CF_TYPE_ID = ctypes.c_ulong CF_INDEX = ctypes.c_long CF_TIME_INTERVAL = ctypes.c_double IO_RETURN = ctypes.c_uint IO_HID_REPORT_TYPE = ctypes.c_uint IO_OPTION_BITS = ctypes.c_uint IO_OBJECT_T = ctypes.c_uint MACH_PORT_T = ctypes.c_uint IO_SERVICE_T = IO_OBJECT_T IO_REGISTRY_ENTRY_T = IO_OBJECT_T IO_HID_MANAGER_REF = ctypes.POINTER(_IOHIDManager) IO_HID_DEVICE_REF = ctypes.POINTER(_IOHIDDevice) # Define C constants K_CF_NUMBER_SINT32_TYPE = 3 K_CF_ALLOCATOR_DEFAULT = None K_IO_MASTER_PORT_DEFAULT = 0 K_IO_HID_REPORT_TYPE_FEATURE = 2 K_IO_RETURN_SUCCESS = 0 # NOTE: find_library doesn't currently work on Big Sur, requiring the hardcoded paths iokit = ctypes.cdll.LoadLibrary( ctypes.util.find_library("IOKit") or "/System/Library/Frameworks/IOKit.framework/IOKit" ) cf = ctypes.cdll.LoadLibrary( ctypes.util.find_library("CoreFoundation") or "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation" ) # Declare C function prototypes cf.CFSetGetValues.restype = None cf.CFSetGetValues.argtypes = [CF_SET_REF, ctypes.POINTER(ctypes.c_void_p)] cf.CFStringCreateWithCString.restype = CF_STRING_REF cf.CFStringCreateWithCString.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32, ] cf.CFGetTypeID.restype = CF_TYPE_ID cf.CFGetTypeID.argtypes = [CF_TYPE_REF] cf.CFNumberGetTypeID.restype = CF_TYPE_ID cf.CFNumberGetValue.restype = ctypes.c_int cf.CFRelease.restype = IO_RETURN cf.CFRelease.argtypes = [CF_TYPE_REF] iokit.IOObjectRelease.argtypes = [IO_OBJECT_T] iokit.IOHIDManagerCreate.restype = IO_HID_MANAGER_REF iokit.IOHIDManagerCreate.argtypes = [CF_ALLOCATOR_REF, IO_OPTION_BITS] iokit.IOHIDManagerCopyDevices.restype = CF_SET_REF iokit.IOHIDManagerCopyDevices.argtypes = [IO_HID_MANAGER_REF] iokit.IOHIDManagerSetDeviceMatching.restype = None iokit.IOHIDManagerSetDeviceMatching.argtypes = [IO_HID_MANAGER_REF, CF_TYPE_REF] iokit.IORegistryEntryIDMatching.restype = CF_MUTABLE_DICTIONARY_REF iokit.IORegistryEntryIDMatching.argtypes = [ctypes.c_uint64] iokit.IORegistryEntryGetRegistryEntryID.restype = IO_RETURN iokit.IORegistryEntryGetRegistryEntryID.argtypes = [ IO_REGISTRY_ENTRY_T, ctypes.POINTER(ctypes.c_uint64), ] iokit.IOHIDDeviceCreate.restype = IO_HID_DEVICE_REF iokit.IOHIDDeviceCreate.argtypes = [CF_ALLOCATOR_REF, IO_SERVICE_T] iokit.IOHIDDeviceClose.restype = IO_RETURN iokit.IOHIDDeviceClose.argtypes = [IO_HID_DEVICE_REF, ctypes.c_uint32] iokit.IOHIDDeviceGetProperty.restype = CF_TYPE_REF iokit.IOHIDDeviceGetProperty.argtypes = [IO_HID_DEVICE_REF, CF_STRING_REF] iokit.IOHIDDeviceSetReport.restype = IO_RETURN iokit.IOHIDDeviceSetReport.argtypes = [ IO_HID_DEVICE_REF, IO_HID_REPORT_TYPE, CF_INDEX, ctypes.c_void_p, CF_INDEX, ] iokit.IOHIDDeviceGetReport.restype = IO_RETURN iokit.IOHIDDeviceGetReport.argtypes = [ IO_HID_DEVICE_REF, IO_HID_REPORT_TYPE, CF_INDEX, ctypes.c_void_p, ctypes.POINTER(CF_INDEX), ] iokit.IOServiceGetMatchingService.restype = IO_SERVICE_T iokit.IOServiceGetMatchingService.argtypes = [MACH_PORT_T, CF_DICTIONARY_REF] class MacHidOtpConnection(OtpConnection): def __init__(self, path): # Resolve the path to device handle device_id = int(path) entry_id = ctypes.c_uint64(device_id) matching_dict = iokit.IORegistryEntryIDMatching(entry_id) device_entry = iokit.IOServiceGetMatchingService( K_IO_MASTER_PORT_DEFAULT, matching_dict ) if not device_entry: raise OSError( f"Device ID {device_id} does not match any HID device on the system" ) self.handle = iokit.IOHIDDeviceCreate(K_CF_ALLOCATOR_DEFAULT, device_entry) if not self.handle: raise OSError("Failed to obtain device handle from registry entry") iokit.IOObjectRelease(device_entry) # Open device result = iokit.IOHIDDeviceOpen(self.handle, 0) if result != K_IO_RETURN_SUCCESS: raise OSError(f"Failed to open device for communication: {result}") def close(self): if self.handle: iokit.IOHIDDeviceClose(self.handle, 0) self.handle = None def receive(self): buf = ctypes.create_string_buffer(8) report_len = CF_INDEX(ctypes.sizeof(buf)) result = iokit.IOHIDDeviceGetReport( self.handle, K_IO_HID_REPORT_TYPE_FEATURE, 0, buf, ctypes.byref(report_len), ) # Non-zero status indicates failure if result != K_IO_RETURN_SUCCESS: raise OSError(f"Failed to read report from device: {result}") data = buf.raw[:] logger.log(LOG_LEVEL.TRAFFIC, "RECV: %s", data.hex()) return data def send(self, data): logger.log(LOG_LEVEL.TRAFFIC, "SEND: %s", data.hex()) result = iokit.IOHIDDeviceSetReport( self.handle, K_IO_HID_REPORT_TYPE_FEATURE, 0, data, len(data), ) # Non-zero status indicates failure if result != K_IO_RETURN_SUCCESS: raise OSError(f"Failed to write report to device: {result}") def get_int_property(dev, key): """Reads int property from the HID device.""" cf_key = cf.CFStringCreateWithCString(None, key, 0) type_ref = iokit.IOHIDDeviceGetProperty(dev, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFNumberGetTypeID(): raise OSError(f"Expected number type, got {cf.CFGetTypeID(type_ref)}") out = ctypes.c_int32() ret = cf.CFNumberGetValue(type_ref, K_CF_NUMBER_SINT32_TYPE, ctypes.byref(out)) if not ret: return None return out.value def get_device_id(device_handle): """Obtains the unique IORegistry entry ID for the device. Args: device_handle: reference to the device Returns: A unique ID for the device, obtained from the IO Registry """ # Obtain device entry ID from IO Registry io_service_obj = iokit.IOHIDDeviceGetService(device_handle) entry_id = ctypes.c_uint64() result = iokit.IORegistryEntryGetRegistryEntryID( io_service_obj, ctypes.byref(entry_id) ) if result != K_IO_RETURN_SUCCESS: raise OSError(f"Failed to obtain IORegistry entry ID: {result}") return entry_id.value def list_devices(): # Init a HID manager hid_mgr = iokit.IOHIDManagerCreate(None, 0) if not hid_mgr: raise OSError("Unable to obtain HID manager reference") try: # Get devices from HID manager iokit.IOHIDManagerSetDeviceMatching(hid_mgr, None) device_set_ref = iokit.IOHIDManagerCopyDevices(hid_mgr) if not device_set_ref: raise OSError("Failed to obtain devices from HID manager") try: num = iokit.CFSetGetCount(device_set_ref) devices = (IO_HID_DEVICE_REF * num)() iokit.CFSetGetValues(device_set_ref, devices) # Retrieve and build descriptor dictionaries for each device devs = [] for dev in devices: vid = get_int_property(dev, HID_DEVICE_PROPERTY_VENDOR_ID) if vid == YUBICO_VID: pid = get_int_property(dev, HID_DEVICE_PROPERTY_PRODUCT_ID) usage = ( get_int_property(dev, HID_DEVICE_PROPERTY_PRIMARY_USAGE_PAGE), get_int_property(dev, HID_DEVICE_PROPERTY_PRIMARY_USAGE), ) device_id = get_device_id(dev) if usage == USAGE_OTP: devs.append( OtpYubiKeyDevice(str(device_id), pid, MacHidOtpConnection) ) return devs finally: cf.CFRelease(device_set_ref) finally: cf.CFRelease(hid_mgr)
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/hid/macos.py
macos.py
# FreeBSD HID driver. # # There are two options to access UHID on FreeBSD: # # hidraw(4) - New method, not enabled by default # on FreeBSD 13.x and earlier # uhid(4) - Classic method, default option on # FreeBSD 13.x and earlier # # To avoid attaching the Yubikey as a keyboard, do: # # usbconfig ugenX.Y add_quirk UQ_KBD_IGNORE # usbconfig ugenX.Y reset # # The list of available devices is shown using `usbconfig list` # You can make these changes permanent by altering loader.conf. # # Starting from FreeBSD 13 hidraw(4) can be enabled using: # # sysrc kld_list+="hidraw hkbd" # cat >>/boot/loader.conf<<EOF # hw.usb.usbhid.enable="1" # hw.usb.quirk.0="0x1050 0x0010 0 0xffff UQ_KBD_IGNORE" # YKS_OTP # hw.usb.quirk.1="0x1050 0x0110 0 0xffff UQ_KBD_IGNORE" # NEO_OTP # hw.usb.quirk.2="0x1050 0x0111 0 0xffff UQ_KBD_IGNORE" # NEO_OTP_CCID # hw.usb.quirk.3="0x1050 0x0114 0 0xffff UQ_KBD_IGNORE" # NEO_OTP_FIDO # hw.usb.quirk.4="0x1050 0x0116 0 0xffff UQ_KBD_IGNORE" # NEO_OTP_FIDO_CCID # hw.usb.quirk.5="0x1050 0x0401 0 0xffff UQ_KBD_IGNORE" # YK4_OTP # hw.usb.quirk.6="0x1050 0x0403 0 0xffff UQ_KBD_IGNORE" # YK4_OTP_FIDO # hw.usb.quirk.7="0x1050 0x0405 0 0xffff UQ_KBD_IGNORE" # YK4_OTP_CCID # hw.usb.quirk.8="0x1050 0x0407 0 0xffff UQ_KBD_IGNORE" # YK4_OTP_FIDO_CCID # hw.usb.quirk.9="0x1050 0x0410 0 0xffff UQ_KBD_IGNORE" # YKP_OTP_FIDO # EOF # reboot # from yubikit.core.otp import OtpConnection from .base import OtpYubiKeyDevice, YUBICO_VID, USAGE_OTP from ctypes.util import find_library import ctypes import glob import fcntl import os import re import sys import struct import logging # Don't typecheck this file on Windows assert sys.platform != "win32" # nosec logger = logging.getLogger(__name__) devdir = "/dev/" # /usr/include/dev/usb/usb_ioctl.h USB_GET_REPORT = 0xC0205517 USB_SET_REPORT = 0x80205518 USB_GET_REPORT_DESC = 0xC0205515 # /usr/include/dev/hid/hidraw.h> HIDIOCGRAWINFO = 0x40085520 HIDIOCGRDESC = 0x2000551F HIDIOCGRDESCSIZE = 0x4004551E HIDIOCGFEATURE_9 = 0xC0095524 HIDIOCSFEATURE_9 = 0x80095523 class HidrawConnection(OtpConnection): """ hidraw(4) is FreeBSD's modern raw access driver, based on usbhid(4). It is available since FreeBSD 13 and can be activated by adding `hw.usb.usbhid.enable="1"` to `/boot/loader.conf`. The actual kernel module is loaded with `kldload hidraw`. """ def __init__(self, path): self.fd = os.open(path, os.O_RDWR) def close(self): os.close(self.fd) def receive(self): buf = bytearray(1 + 8) fcntl.ioctl(self.fd, HIDIOCGFEATURE_9, buf, True) return buf[1:] def send(self, data): buf = bytes([0]) + data fcntl.ioctl(self.fd, HIDIOCSFEATURE_9, buf) @staticmethod def get_info(dev): buf = bytearray(4 + 2 + 2) fcntl.ioctl(dev, HIDIOCGRAWINFO, buf, True) return struct.unpack("<IHH", buf) @staticmethod def get_descriptor(dev): buf = bytearray(4) fcntl.ioctl(dev, HIDIOCGRDESCSIZE, buf, True) size = struct.unpack("<I", buf)[0] buf += bytearray(size) fcntl.ioctl(dev, HIDIOCGRDESC, buf, True) return buf[4:] @staticmethod def get_usage(dev): buf = HidrawConnection.get_descriptor(dev) usage, usage_page = (None, None) while buf: head, buf = buf[0], buf[1:] typ, size = 0xFC & head, 0x03 & head value, buf = buf[:size], buf[size:] if typ == 4: # Usage page usage_page = struct.unpack("<I", value.ljust(4, b"\0"))[0] if usage is not None: return usage_page, usage elif typ == 8: # Usage usage = struct.unpack("<I", value.ljust(4, b"\0"))[0] if usage_page is not None: return usage_page, usage @staticmethod def list_devices(): devices = [] for hidraw in glob.glob(devdir + "hidraw?*"): try: with open(hidraw, "rb") as f: bustype, vid, pid = HidrawConnection.get_info(f) if vid == YUBICO_VID and HidrawConnection.get_usage(f) == USAGE_OTP: devices.append(OtpYubiKeyDevice(hidraw, pid, HidrawConnection)) except Exception as e: logger.debug("Failed opening HID device", exc_info=e) continue return devices # For UhidConnection libc = ctypes.CDLL(find_library("c")) class usb_gen_descriptor(ctypes.Structure): _fields_ = [ ( "ugd_data", ctypes.c_void_p, ), ("ugd_lang_id", ctypes.c_uint16), ("ugd_maxlen", ctypes.c_uint16), ("ugd_actlen", ctypes.c_uint16), ("ugd_offset", ctypes.c_uint16), ("ugd_config_index", ctypes.c_uint8), ("ugd_string_index", ctypes.c_uint8), ("ugd_iface_index", ctypes.c_uint8), ("ugd_altif_index", ctypes.c_uint8), ("ugd_endpt_index", ctypes.c_uint8), ("ugd_report_type", ctypes.c_uint8), ("reserved", ctypes.c_uint8 * 8), ] class UhidConnection(OtpConnection): """ uhid(4) is FreeBSD's classic USB hid access driver and enabled by default in FreeBSD 13.x and earlier. """ def __init__(self, path): self.fd = os.open(path, os.O_RDWR) def close(self): os.close(self.fd) def receive(self): buf = ctypes.create_string_buffer(9) desc = usb_gen_descriptor( ugd_data=ctypes.addressof(buf), ugd_maxlen=ctypes.sizeof(buf), ugd_report_type=3, ) ret = libc.ioctl(self.fd, USB_GET_REPORT, ctypes.pointer(desc)) if ret != 0: raise ValueError("ioctl failed: " + str(ret)) return buf[:-1] def send(self, data): buf = ctypes.create_string_buffer(8) for i in range(0, len(data)): buf[i] = data[i] desc = usb_gen_descriptor( ugd_data=ctypes.addressof(buf), ugd_maxlen=len(buf), ugd_report_type=0x3, ) ret = libc.ioctl(self.fd, USB_SET_REPORT, ctypes.pointer(desc)) if ret != 0: raise ValueError("ioctl failed: " + str(ret)) @staticmethod def get_usage(dev): c_data = ctypes.create_string_buffer(4096) desc = usb_gen_descriptor( ugd_data=ctypes.addressof(c_data), ugd_maxlen=ctypes.sizeof(c_data), ugd_report_type=3, ) ret = libc.ioctl(dev, USB_GET_REPORT_DESC, ctypes.pointer(desc)) if ret != 0: raise ValueError("ioctl failed") REPORT_DESCRIPTOR_KEY_MASK = 0xFC SIZE_MASK = ~REPORT_DESCRIPTOR_KEY_MASK USAGE_PAGE = 0x04 USAGE = 0x08 data = c_data.raw usage, usage_page = (None, None) while data and not (usage and usage_page): head, data = struct.unpack_from(">B", data)[0], data[1:] key, size = REPORT_DESCRIPTOR_KEY_MASK & head, SIZE_MASK & head value = struct.unpack_from("<I", data[:size].ljust(4, b"\0"))[0] data = data[size:] if key == USAGE_PAGE and not usage_page: usage_page = value elif key == USAGE and not usage: usage = value return (usage_page, usage) @staticmethod def get_info(index): vendor_re = re.compile("vendor=(0x[0-9a-fA-F]+)") product_re = re.compile("product=(0x[0-9a-fA-F]+)") sernum_re = re.compile('sernum="([^"]+)') pnpinfo = ("dev.uhid." + index + ".%pnpinfo").encode() ovalue = ctypes.create_string_buffer(1024) olen = ctypes.c_size_t(ctypes.sizeof(ovalue)) key = ctypes.c_char_p(pnpinfo) retval = libc.sysctlbyname(key, ovalue, ctypes.byref(olen), None, None) if retval != 0: raise IOError("sysctlbyname failed") value = ovalue.value[: olen.value].decode() m = vendor_re.search(value) vid = int(m.group(1), 16) if m else None m = product_re.search(value) pid = int(m.group(1), 16) if m else None m = sernum_re.search(value) serial = m.group(1) if m else None return (vid, pid, serial) @staticmethod def list_devices(): devices = [] for uhid in glob.glob(devdir + "uhid?*"): index = uhid[len(devdir) + len("uhid") :] if not index.isdigit(): continue try: (vid, pid, serial) = UhidConnection.get_info(index) if vid == YUBICO_VID: with open(uhid, "rb") as f: if UhidConnection.get_usage(f.fileno()) == USAGE_OTP: devices.append(OtpYubiKeyDevice(uhid, pid, UhidConnection)) except Exception as e: logger.debug("Failed opening HID device", exc_info=e) continue return devices def list_devices(): devices = HidrawConnection.list_devices() if not devices: devices = UhidConnection.list_devices() return devices
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/hid/freebsd.py
freebsd.py
from yubikit.core.otp import OtpConnection from yubikit.logging import LOG_LEVEL from .base import OtpYubiKeyDevice, YUBICO_VID, USAGE_OTP from typing import Set import glob import fcntl import struct import logging import sys # Don't typecheck this file on Windows assert sys.platform != "win32" # nosec logger = logging.getLogger(__name__) # usb_ioctl.h USB_GET_REPORT = 0xC0094807 USB_SET_REPORT = 0xC0094806 # hidraw.h HIDIOCGRAWINFO = 0x80084803 HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESC = 0x90044802 class HidrawConnection(OtpConnection): def __init__(self, path): self.handle = open(path, "wb") def close(self): self.handle.close() def receive(self): buf = bytearray(1 + 8) fcntl.ioctl(self.handle, USB_GET_REPORT, buf, True) data = buf[1:] logger.log(LOG_LEVEL.TRAFFIC, "RECV: %s", data.hex()) return data def send(self, data): logger.log(LOG_LEVEL.TRAFFIC, "SEND: %s", data.hex()) buf = bytearray([0]) # Prepend the report ID. buf.extend(data) fcntl.ioctl(self.handle, USB_SET_REPORT, buf, True) def get_info(dev): buf = bytearray(4 + 2 + 2) fcntl.ioctl(dev, HIDIOCGRAWINFO, buf, True) return struct.unpack("<IHH", buf) def get_descriptor(dev): buf = bytearray(4) fcntl.ioctl(dev, HIDIOCGRDESCSIZE, buf, True) size = struct.unpack("<I", buf)[0] buf += bytearray(size) fcntl.ioctl(dev, HIDIOCGRDESC, buf, True) return buf[4:] def get_usage(dev): buf = get_descriptor(dev) usage, usage_page = (None, None) while buf: head, buf = buf[0], buf[1:] typ, size = 0xFC & head, 0x03 & head value, buf = buf[:size], buf[size:] if typ == 4: # Usage page usage_page = struct.unpack("<I", value.ljust(4, b"\0"))[0] if usage is not None: return usage_page, usage elif typ == 8: # Usage usage = struct.unpack("<I", value.ljust(4, b"\0"))[0] if usage_page is not None: return usage_page, usage # Cache for continuously failing devices _failed_cache: Set[str] = set() def list_devices(): stale = set(_failed_cache) devices = [] for hidraw in glob.glob("/dev/hidraw*"): stale.discard(hidraw) try: with open(hidraw, "rb") as f: bustype, vid, pid = get_info(f) if vid == YUBICO_VID and get_usage(f) == USAGE_OTP: devices.append(OtpYubiKeyDevice(hidraw, pid, HidrawConnection)) except Exception: if hidraw not in _failed_cache: logger.debug( f"Couldn't read HID descriptor for {hidraw}", exc_info=True ) _failed_cache.add(hidraw) continue # Remove entries from the cache that were not seen _failed_cache.difference_update(hidraw) return devices
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/hid/linux.py
linux.py
from ..base import YkmanDevice, PID from .base import OtpYubiKeyDevice from yubikit.core import TRANSPORT from typing import List, Callable import sys import logging logger = logging.getLogger(__name__) if sys.platform.startswith("linux"): from . import linux as backend elif sys.platform.startswith("win32"): from . import windows as backend elif sys.platform.startswith("darwin"): from . import macos as backend elif sys.platform.startswith("freebsd"): from . import freebsd as backend else: class backend: @staticmethod def list_devices(): raise NotImplementedError( "OTP HID support is not implemented on this platform" ) list_otp_devices: Callable[[], List[OtpYubiKeyDevice]] = backend.list_devices try: from fido2.hid import list_descriptors, open_connection, CtapHidDevice class CtapYubiKeyDevice(YkmanDevice): """YubiKey FIDO USB HID device""" def __init__(self, descriptor): super(CtapYubiKeyDevice, self).__init__( TRANSPORT.USB, descriptor.path, PID(descriptor.pid) ) self.descriptor = descriptor def supports_connection(self, connection_type): return issubclass(CtapHidDevice, connection_type) def open_connection(self, connection_type): if self.supports_connection(connection_type): return CtapHidDevice(self.descriptor, open_connection(self.descriptor)) return super(CtapYubiKeyDevice, self).open_connection(connection_type) def list_ctap_devices() -> List[CtapYubiKeyDevice]: devs = [] for desc in list_descriptors(): if desc.vid == 0x1050: try: devs.append(CtapYubiKeyDevice(desc)) except ValueError: logger.debug(f"Unsupported Yubico device with PID: {desc.pid:02x}") return devs except Exception: # CTAP not supported on this platform class CtapYubiKeyDevice(YkmanDevice): # type: ignore def __init__(self, *args, **kwargs): raise NotImplementedError( "CTAP HID support is not implemented on this platform" ) def list_ctap_devices() -> List[CtapYubiKeyDevice]: raise NotImplementedError( "CTAP HID support is not implemented on this platform" )
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/hid/__init__.py
__init__.py
from .base import OtpYubiKeyDevice, YUBICO_VID, USAGE_OTP from yubikit.core.otp import OtpConnection from yubikit.logging import LOG_LEVEL from ctypes import wintypes, LibraryLoader from typing import Dict, cast import ctypes import platform import logging import re import sys # Only typecheck this file on Windows assert sys.platform == "win32" # nosec from ctypes import WinDLL, WinError # noqa: E402 logger = logging.getLogger(__name__) # Load relevant DLLs windll = LibraryLoader(WinDLL) hid = windll.Hid setupapi = windll.SetupAPI kernel32 = windll.Kernel32 # Various structs that are used in the Windows APIs we call class GUID(ctypes.Structure): _fields_ = [ ("Data1", ctypes.c_ulong), ("Data2", ctypes.c_ushort), ("Data3", ctypes.c_ushort), ("Data4", ctypes.c_ubyte * 8), ] # On Windows, SetupAPI.h packs structures differently in 64bit and # 32bit mode. In 64-bit mode, the structures are packed on 8 byte # boundaries, while in 32-bit mode, they are packed on 1 byte boundaries. # This is important to get right for some API calls that fill out these # structures. if platform.architecture()[0] == "64bit": SETUPAPI_PACK = 8 elif platform.architecture()[0] == "32bit": SETUPAPI_PACK = 1 else: raise OSError(f"Unknown architecture: {platform.architecture()[0]}") class DeviceInterfaceData(ctypes.Structure): _fields_ = [ ("cbSize", wintypes.DWORD), ("InterfaceClassGuid", GUID), ("Flags", wintypes.DWORD), ("Reserved", ctypes.POINTER(ctypes.c_ulong)), ] _pack_ = SETUPAPI_PACK class DeviceInterfaceDetailData(ctypes.Structure): _fields_ = [("cbSize", wintypes.DWORD), ("DevicePath", ctypes.c_byte * 1)] _pack_ = SETUPAPI_PACK class HidAttributes(ctypes.Structure): _fields_ = [ ("Size", ctypes.c_ulong), ("VendorID", ctypes.c_ushort), ("ProductID", ctypes.c_ushort), ("VersionNumber", ctypes.c_ushort), ] class HidCapabilities(ctypes.Structure): _fields_ = [ ("Usage", ctypes.c_ushort), ("UsagePage", ctypes.c_ushort), ("InputReportByteLength", ctypes.c_ushort), ("OutputReportByteLength", ctypes.c_ushort), ("FeatureReportByteLength", ctypes.c_ushort), ("Reserved", ctypes.c_ushort * 17), ("NotUsed", ctypes.c_ushort * 10), ] # Various void* aliases for readability. HDEVINFO = ctypes.c_void_p HANDLE = ctypes.c_void_p PHIDP_PREPARSED_DATA = ctypes.c_void_p # pylint: disable=invalid-name # This is a HANDLE. # INVALID_HANDLE_VALUE = 0xFFFFFFFF INVALID_HANDLE_VALUE = (1 << 8 * ctypes.sizeof(ctypes.c_void_p)) - 1 # Status codes FILE_SHARE_READ = 0x00000001 FILE_SHARE_WRITE = 0x00000002 OPEN_EXISTING = 0x03 NTSTATUS = ctypes.c_long HIDP_STATUS_SUCCESS = 0x00110000 # CreateFile Flags GENERIC_WRITE = 0x40000000 GENERIC_READ = 0x80000000 DIGCF_DEVICEINTERFACE = 0x10 DIGCF_PRESENT = 0x02 # Function signatures hid.HidD_GetHidGuid.restype = None hid.HidD_GetHidGuid.argtypes = [ctypes.POINTER(GUID)] hid.HidD_GetAttributes.restype = wintypes.BOOLEAN hid.HidD_GetAttributes.argtypes = [HANDLE, ctypes.POINTER(HidAttributes)] hid.HidD_GetPreparsedData.restype = wintypes.BOOLEAN hid.HidD_GetPreparsedData.argtypes = [HANDLE, ctypes.POINTER(PHIDP_PREPARSED_DATA)] hid.HidD_FreePreparsedData.restype = wintypes.BOOLEAN hid.HidD_FreePreparsedData.argtypes = [PHIDP_PREPARSED_DATA] hid.HidD_GetProductString.restype = wintypes.BOOLEAN hid.HidD_GetProductString.argtypes = [HANDLE, ctypes.c_void_p, ctypes.c_ulong] hid.HidP_GetCaps.restype = NTSTATUS hid.HidP_GetCaps.argtypes = [PHIDP_PREPARSED_DATA, ctypes.POINTER(HidCapabilities)] hid.HidD_GetFeature.restype = wintypes.BOOL hid.HidD_GetFeature.argtypes = [HANDLE, ctypes.c_void_p, ctypes.c_ulong] hid.HidD_SetFeature.restype = wintypes.BOOL hid.HidD_SetFeature.argtypes = [HANDLE, ctypes.c_void_p, ctypes.c_ulong] setupapi.SetupDiGetClassDevsA.argtypes = [ ctypes.POINTER(GUID), ctypes.c_char_p, wintypes.HWND, wintypes.DWORD, ] setupapi.SetupDiGetClassDevsA.restype = HDEVINFO setupapi.SetupDiEnumDeviceInterfaces.restype = wintypes.BOOL setupapi.SetupDiEnumDeviceInterfaces.argtypes = [ HDEVINFO, ctypes.c_void_p, ctypes.POINTER(GUID), wintypes.DWORD, ctypes.POINTER(DeviceInterfaceData), ] setupapi.SetupDiGetDeviceInterfaceDetailA.restype = wintypes.BOOL setupapi.SetupDiGetDeviceInterfaceDetailA.argtypes = [ HDEVINFO, ctypes.POINTER(DeviceInterfaceData), ctypes.POINTER(DeviceInterfaceDetailData), wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p, ] setupapi.SetupDiDestroyDeviceInfoList.restype = wintypes.BOOL setupapi.SetupDiDestroyDeviceInfoList.argtypes = [ HDEVINFO, ] kernel32.CreateFileA.restype = HANDLE kernel32.CreateFileA.argtypes = [ ctypes.c_char_p, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, HANDLE, ] kernel32.CloseHandle.restype = wintypes.BOOL kernel32.CloseHandle.argtypes = [HANDLE] class WinHidOtpConnection(OtpConnection): def __init__(self, path): self.handle = kernel32.CreateFileA( path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, 0, None, ) if self.handle == INVALID_HANDLE_VALUE: raise WinError() def close(self): if self.handle: kernel32.CloseHandle(self.handle) self.handle = None def receive(self): buf = ctypes.create_string_buffer(9) result = hid.HidD_GetFeature(self.handle, buf, ctypes.sizeof(buf)) if not result: raise WinError() data = buf.raw[1:] logger.log(LOG_LEVEL.TRAFFIC, "RECV: %s", data.hex()) return data def send(self, data): logger.log(LOG_LEVEL.TRAFFIC, "SEND: %s", data.hex()) buf = ctypes.create_string_buffer(b"\0" + data) result = hid.HidD_SetFeature(self.handle, buf, ctypes.sizeof(buf)) if not result: raise WinError() def get_vid_pid(device): attributes = HidAttributes() result = hid.HidD_GetAttributes(device, ctypes.byref(attributes)) if not result: raise WinError() return attributes.VendorID, attributes.ProductID def get_usage(device): preparsed_data = PHIDP_PREPARSED_DATA(0) ret = hid.HidD_GetPreparsedData(device, ctypes.byref(preparsed_data)) if not ret: raise WinError() try: caps = HidCapabilities() ret = hid.HidP_GetCaps(preparsed_data, ctypes.byref(caps)) if ret != HIDP_STATUS_SUCCESS: raise WinError() return caps.UsagePage, caps.Usage finally: hid.HidD_FreePreparsedData(preparsed_data) VID_RE = re.compile(rb"\Wvid_%04x\W" % YUBICO_VID) PID_RE = re.compile(rb"\Wpid_([a-z0-9]{4})\W") def list_paths(): hid_guid = GUID() hid.HidD_GetHidGuid(ctypes.byref(hid_guid)) collection = setupapi.SetupDiGetClassDevsA( ctypes.byref(hid_guid), None, None, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT ) try: index = 0 interface_info = DeviceInterfaceData() interface_info.cbSize = ctypes.sizeof(DeviceInterfaceData) paths = [] while True: result = setupapi.SetupDiEnumDeviceInterfaces( collection, 0, ctypes.byref(hid_guid), index, ctypes.byref(interface_info), ) index += 1 if not result: break detail_len_dw = wintypes.DWORD() result = setupapi.SetupDiGetDeviceInterfaceDetailA( collection, ctypes.byref(interface_info), None, 0, ctypes.byref(detail_len_dw), None, ) if result: raise WinError() detail_len = detail_len_dw.value if detail_len == 0: # skip this device, some kind of error continue buf = ctypes.create_string_buffer(detail_len) interface_detail = DeviceInterfaceDetailData.from_buffer(buf) interface_detail.cbSize = ctypes.sizeof(DeviceInterfaceDetailData) result = setupapi.SetupDiGetDeviceInterfaceDetailA( collection, ctypes.byref(interface_info), ctypes.byref(interface_detail), detail_len, None, None, ) if not result: raise WinError() path = ctypes.string_at(ctypes.addressof(interface_detail.DevicePath)) if VID_RE.search(path): pid_match = PID_RE.search(path) if pid_match: paths.append((int(pid_match.group(1), 16), path)) return paths finally: setupapi.SetupDiDestroyDeviceInfoList(collection) _SKIP = cast(OtpYubiKeyDevice, object()) _device_cache: Dict[bytes, OtpYubiKeyDevice] = {} def list_devices(): stale = set(_device_cache) devices = [] for pid, path in list_paths(): stale.discard(path) # Check if path already cached dev = _device_cache.get(path) if dev: if dev is not _SKIP: devices.append(dev) continue device = kernel32.CreateFileA( path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, 0, None, ) if device == INVALID_HANDLE_VALUE: logger.debug("Couldn't read HID descriptor for %s", path) else: try: usage = get_usage(device) if usage == USAGE_OTP: dev = OtpYubiKeyDevice(path, pid, WinHidOtpConnection) _device_cache[path] = dev devices.append(dev) continue except Exception: logger.debug("Couldn't read Usage Page for %s:", path, exc_info=True) finally: kernel32.CloseHandle(device) _device_cache[path] = _SKIP # Remove entries from the cache that were not seen for path in stale: del _device_cache[path] return devices
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/hid/windows.py
windows.py
from ..base import YkmanDevice from yubikit.core import TRANSPORT, YUBIKEY, PID from yubikit.core.smartcard import SmartCardConnection from yubikit.management import USB_INTERFACE from yubikit.logging import LOG_LEVEL from smartcard import System from smartcard.Exceptions import CardConnectionException from smartcard.pcsc.PCSCExceptions import ListReadersException from smartcard.pcsc.PCSCContext import PCSCContext from fido2.pcsc import CtapPcscDevice from time import sleep import subprocess # nosec import logging logger = logging.getLogger(__name__) YK_READER_NAME = "yubico yubikey" # Figure out what the PID should be based on the reader name def _pid_from_name(name): if YK_READER_NAME not in name.lower(): return None interfaces = USB_INTERFACE(0) for iface in USB_INTERFACE: if iface.name in name: interfaces |= iface if "U2F" in name: interfaces |= USB_INTERFACE.FIDO key_type = YUBIKEY.NEO if "NEO" in name else YUBIKEY.YK4 return PID.of(key_type, interfaces) class ScardYubiKeyDevice(YkmanDevice): """YubiKey Smart card device""" def __init__(self, reader): # Base transport on reader name: NFC readers will have a different name if YK_READER_NAME in reader.name.lower(): transport = TRANSPORT.USB else: transport = TRANSPORT.NFC super(ScardYubiKeyDevice, self).__init__( transport, reader.name, _pid_from_name(reader.name) ) self.reader = reader def supports_connection(self, connection_type): if issubclass(CtapPcscDevice, connection_type): return self.transport == TRANSPORT.NFC return issubclass(ScardSmartCardConnection, connection_type) def open_connection(self, connection_type): if issubclass(ScardSmartCardConnection, connection_type): return self._open_smartcard_connection() elif issubclass(CtapPcscDevice, connection_type): if self.transport == TRANSPORT.NFC: return CtapPcscDevice(self.reader.createConnection(), self.reader.name) return super(ScardYubiKeyDevice, self).open_connection(connection_type) def _open_smartcard_connection(self) -> SmartCardConnection: try: return ScardSmartCardConnection(self.reader.createConnection()) except CardConnectionException as e: if kill_scdaemon(): return ScardSmartCardConnection(self.reader.createConnection()) raise e class ScardSmartCardConnection(SmartCardConnection): def __init__(self, connection): self.connection = connection connection.connect() atr = connection.getATR() self._transport = ( TRANSPORT.USB if atr and atr[1] & 0xF0 == 0xF0 else TRANSPORT.NFC ) @property def transport(self): return self._transport def close(self): self.connection.disconnect() def send_and_receive(self, apdu): """Sends a command APDU and returns the response data and sw""" logger.log(LOG_LEVEL.TRAFFIC, "SEND: %s", apdu.hex()) data, sw1, sw2 = self.connection.transmit(list(apdu)) logger.log( LOG_LEVEL.TRAFFIC, "RECV: %s SW=%02x%02x", bytes(data).hex(), sw1, sw2 ) return bytes(data), sw1 << 8 | sw2 def kill_scdaemon(): killed = False try: # Works for Windows. from win32com.client import GetObject from win32api import OpenProcess, CloseHandle, TerminateProcess wmi = GetObject("winmgmts:") ps = wmi.InstancesOf("Win32_Process") for p in ps: if p.Properties_("Name").Value == "scdaemon.exe": pid = p.Properties_("ProcessID").Value handle = OpenProcess(1, False, pid) TerminateProcess(handle, -1) CloseHandle(handle) killed = True except ImportError: # Works for Linux and OS X. return_code = subprocess.call(["pkill", "-9", "scdaemon"]) # nosec if return_code == 0: killed = True if killed: sleep(0.1) return killed def list_readers(): try: return System.readers() except ListReadersException: # If the PCSC system has restarted the context might be stale, try # forcing a new context (This happens on Windows if the last reader is # removed): PCSCContext.instance = None return System.readers() def list_devices(name_filter=None): name_filter = YK_READER_NAME if name_filter is None else name_filter devices = [] for reader in list_readers(): if name_filter.lower() in reader.name.lower(): devices.append(ScardYubiKeyDevice(reader)) return devices
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/pcsc/__init__.py
__init__.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for US English keyboard layout""" SHIFT = 0x80 scancodes = { "a": 0x04, "b": 0x05, "c": 0x06, "d": 0x07, "e": 0x08, "f": 0x09, "g": 0x0A, "h": 0x0B, "i": 0x0C, "j": 0x0D, "k": 0x0E, "l": 0x0F, "m": 0x10, "n": 0x11, "o": 0x12, "p": 0x13, "q": 0x14, "r": 0x15, "s": 0x16, "t": 0x17, "u": 0x18, "v": 0x19, "w": 0x1A, "x": 0x1B, "y": 0x1C, "z": 0x1D, "A": 0x04 | SHIFT, "B": 0x05 | SHIFT, "C": 0x06 | SHIFT, "D": 0x07 | SHIFT, "E": 0x08 | SHIFT, "F": 0x09 | SHIFT, "G": 0x0A | SHIFT, "H": 0x0B | SHIFT, "I": 0x0C | SHIFT, "J": 0x0D | SHIFT, "K": 0x0E | SHIFT, "L": 0x0F | SHIFT, "M": 0x10 | SHIFT, "N": 0x11 | SHIFT, "O": 0x12 | SHIFT, "P": 0x13 | SHIFT, "Q": 0x14 | SHIFT, "R": 0x15 | SHIFT, "S": 0x16 | SHIFT, "T": 0x17 | SHIFT, "U": 0x18 | SHIFT, "V": 0x19 | SHIFT, "W": 0x1A | SHIFT, "X": 0x1B | SHIFT, "Y": 0x1C | SHIFT, "Z": 0x1D | SHIFT, "0": 0x27, "1": 0x1E, "2": 0x1F, "3": 0x20, "4": 0x21, "5": 0x22, "6": 0x23, "7": 0x24, "8": 0x25, "9": 0x26, "\t": 0x2B, "\n": 0x28, "!": 0x1E | SHIFT, '"': 0x34 | SHIFT, "#": 0x20 | SHIFT, "$": 0x21 | SHIFT, "%": 0x22 | SHIFT, "&": 0x24 | SHIFT, "'": 0x34, "`": 0x35, "(": 0x26 | SHIFT, ")": 0x27 | SHIFT, "*": 0x25 | SHIFT, "+": 0x2E | SHIFT, ",": 0x36, "-": 0x2D, ".": 0x37, "/": 0x38, ":": 0x33 | SHIFT, ";": 0x33, "<": 0x36 | SHIFT, "=": 0x2E, ">": 0x37 | SHIFT, "?": 0x38 | SHIFT, "@": 0x1F | SHIFT, "[": 0x2F, "\\": 0x32, "]": 0x30, "^": 0xA3, "_": 0xAD, "{": 0x2F | SHIFT, "}": 0x30 | SHIFT, "|": 0x32 | SHIFT, "~": 0x35 | SHIFT, " ": 0x2C, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/us.py
us.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for BÉPO (fr dvorak) keyboard layout""" SHIFT = 0x80 scancodes = { "\t": 0x2B | SHIFT, "\n": 0x28 | SHIFT, " ": 0x2C, "!": 0x1C | SHIFT, '"': 0x1E, "#": 0x35 | SHIFT, "$": 0x35, "%": 0x2E, "'": 0x11, "(": 0x21, ")": 0x22, "*": 0x27, "+": 0x24, ",": 0x0A, "-": 0x25, ".": 0x19, "/": 0x26, "0": 0x27 | SHIFT, "1": 0x1E | SHIFT, "2": 0x1F | SHIFT, "3": 0x20 | SHIFT, "4": 0x21 | SHIFT, "5": 0x22 | SHIFT, "6": 0x23 | SHIFT, "7": 0x24 | SHIFT, "8": 0x25 | SHIFT, "9": 0x26 | SHIFT, ":": 0x19 | SHIFT, ";": 0x0A | SHIFT, "=": 0x2D, "?": 0x11 | SHIFT, "@": 0x23, "A": 0x04 | SHIFT, "B": 0x14 | SHIFT, "C": 0x0B | SHIFT, "D": 0x0C | SHIFT, "E": 0x09 | SHIFT, "F": 0x38 | SHIFT, "G": 0x36 | SHIFT, "H": 0x37 | SHIFT, "I": 0x07 | SHIFT, "J": 0x13 | SHIFT, "K": 0x05 | SHIFT, "L": 0x12 | SHIFT, "M": 0x34 | SHIFT, "N": 0x33 | SHIFT, "O": 0x15 | SHIFT, "P": 0x08 | SHIFT, "Q": 0x10 | SHIFT, "R": 0x0F | SHIFT, "S": 0x0E | SHIFT, "T": 0x0D | SHIFT, "U": 0x16 | SHIFT, "V": 0x18 | SHIFT, "W": 0x30 | SHIFT, "X": 0x06 | SHIFT, "Y": 0x1B | SHIFT, "Z": 0x2F | SHIFT, "`": 0x2E | SHIFT, "a": 0x04, "b": 0x14, "c": 0x0B, "d": 0x0C, "e": 0x09, "f": 0x38, "g": 0x36, "h": 0x37, "i": 0x07, "j": 0x13, "k": 0x05, "l": 0x12, "m": 0x34, "n": 0x33, "o": 0x15, "p": 0x08, "q": 0x10, "r": 0x0F, "s": 0x0E, "t": 0x0D, "u": 0x16, "v": 0x18, "w": 0x30, "x": 0x06, "y": 0x1B, "z": 0x2F, "\xa0": 0x2C | SHIFT, "«": 0x1F, "°": 0x2D | SHIFT, "»": 0x20, "À": 0x1D | SHIFT, "Ç": 0x31 | SHIFT, "È": 0x17 | SHIFT, "É": 0x1A | SHIFT, "Ê": 0x64 | SHIFT, "à": 0x1D, "ç": 0x31, "è": 0x17, "é": 0x1A, "ê": 0x64, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/bepo.py
bepo.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for keyboard layout based on Modhex. Note that this layouts allows both upper and lowercase characters.""" SHIFT = 0x80 scancodes = { "b": 0x05, "c": 0x06, "d": 0x07, "e": 0x08, "f": 0x09, "g": 0x0A, "h": 0x0B, "i": 0x0C, "j": 0x0D, "k": 0x0E, "l": 0x0F, "n": 0x11, "r": 0x15, "t": 0x17, "u": 0x18, "v": 0x19, "B": 0x05 | SHIFT, "C": 0x06 | SHIFT, "D": 0x07 | SHIFT, "E": 0x08 | SHIFT, "F": 0x09 | SHIFT, "G": 0x0A | SHIFT, "H": 0x0B | SHIFT, "I": 0x0C | SHIFT, "J": 0x0D | SHIFT, "K": 0x0E | SHIFT, "L": 0x0F | SHIFT, "N": 0x11 | SHIFT, "R": 0x15 | SHIFT, "T": 0x17 | SHIFT, "U": 0x18 | SHIFT, "V": 0x19 | SHIFT, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/modhex.py
modhex.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for UK English keyboard layout""" SHIFT = 0x80 scancodes = { "a": 0x04, "b": 0x05, "c": 0x06, "d": 0x07, "e": 0x08, "f": 0x09, "g": 0x0A, "h": 0x0B, "i": 0x0C, "j": 0x0D, "k": 0x0E, "l": 0x0F, "m": 0x10, "n": 0x11, "o": 0x12, "p": 0x13, "q": 0x14, "r": 0x15, "s": 0x16, "t": 0x17, "u": 0x18, "v": 0x19, "w": 0x1A, "x": 0x1B, "y": 0x1C, "z": 0x1D, "A": 0x04 | SHIFT, "B": 0x05 | SHIFT, "C": 0x06 | SHIFT, "D": 0x07 | SHIFT, "E": 0x08 | SHIFT, "F": 0x09 | SHIFT, "G": 0x0A | SHIFT, "H": 0x0B | SHIFT, "I": 0x0C | SHIFT, "J": 0x0D | SHIFT, "K": 0x0E | SHIFT, "L": 0x0F | SHIFT, "M": 0x10 | SHIFT, "N": 0x11 | SHIFT, "O": 0x12 | SHIFT, "P": 0x13 | SHIFT, "Q": 0x14 | SHIFT, "R": 0x15 | SHIFT, "S": 0x16 | SHIFT, "T": 0x17 | SHIFT, "U": 0x18 | SHIFT, "V": 0x19 | SHIFT, "W": 0x1A | SHIFT, "X": 0x1B | SHIFT, "Y": 0x1C | SHIFT, "Z": 0x1D | SHIFT, "0": 0x27, "1": 0x1E, "2": 0x1F, "3": 0x20, "4": 0x21, "5": 0x22, "6": 0x23, "7": 0x24, "8": 0x25, "9": 0x26, "\t": 0x2B, "\n": 0x28, "!": 0x1E | SHIFT, "@": 0x34 | SHIFT, "£": 0x20 | SHIFT, "$": 0x21 | SHIFT, "%": 0x22 | SHIFT, "&": 0x24 | SHIFT, "'": 0x34, "`": 0x35, "(": 0x26 | SHIFT, ")": 0x27 | SHIFT, "*": 0x25 | SHIFT, "+": 0x2E | SHIFT, ",": 0x36, "-": 0x2D, ".": 0x37, "/": 0x38, ":": 0x33 | SHIFT, ";": 0x33, "<": 0x36 | SHIFT, "=": 0x2E, ">": 0x37 | SHIFT, "?": 0x38 | SHIFT, '"': 0x1F | SHIFT, "[": 0x2F, "#": 0x32, "]": 0x30, "^": 0xA3, "_": 0xAD, "{": 0x2F | SHIFT, "}": 0x30 | SHIFT, "~": 0x32 | SHIFT, "¬": 0x35 | SHIFT, " ": 0x2C, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/uk.py
uk.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for FR French (AZERTY) keyboard layout""" SHIFT = 0x80 scancodes = { "a": 0x14, "b": 0x05, "c": 0x06, "d": 0x07, "e": 0x08, "f": 0x09, "g": 0x0A, "h": 0x0B, "i": 0x0C, "j": 0x0D, "k": 0x0E, "l": 0x0F, "m": 0x33, "n": 0x11, "o": 0x12, "p": 0x13, "q": 0x04, "r": 0x15, "s": 0x16, "t": 0x17, "u": 0x18, "v": 0x19, "w": 0x1D, "x": 0x1B, "y": 0x1C, "z": 0x1A, "A": 0x14 | SHIFT, "B": 0x05 | SHIFT, "C": 0x06 | SHIFT, "D": 0x07 | SHIFT, "E": 0x08 | SHIFT, "F": 0x09 | SHIFT, "G": 0x0A | SHIFT, "H": 0x0B | SHIFT, "I": 0x0C | SHIFT, "J": 0x0D | SHIFT, "K": 0x0E | SHIFT, "L": 0x0F | SHIFT, "M": 0x33 | SHIFT, "N": 0x11 | SHIFT, "O": 0x12 | SHIFT, "P": 0x13 | SHIFT, "Q": 0x04 | SHIFT, "R": 0x15 | SHIFT, "S": 0x16 | SHIFT, "T": 0x17 | SHIFT, "U": 0x18 | SHIFT, "V": 0x19 | SHIFT, "W": 0x1D | SHIFT, "X": 0x1B | SHIFT, "Y": 0x1C | SHIFT, "Z": 0x1A | SHIFT, "0": 0x27 | SHIFT, "1": 0x1E | SHIFT, "2": 0x1F | SHIFT, "3": 0x20 | SHIFT, "4": 0x21 | SHIFT, "5": 0x22 | SHIFT, "6": 0x23 | SHIFT, "7": 0x24 | SHIFT, "8": 0x25 | SHIFT, "9": 0x26 | SHIFT, "\t": 0x2B, "\n": 0x28, " ": 0x2C, "!": 0x38, '"': 0x20, "$": 0x30, "%": 0x34 | SHIFT, "&": 0x1E, "'": 0x21, "(": 0x22, ")": 0x2D, "*": 0x31, "+": 0x2E | SHIFT, ",": 0x10, "-": 0x23, ".": 0x36 | SHIFT, "/": 0x37 | SHIFT, ":": 0x37, ";": 0x36, "<": 0x64, "=": 0x2E, "_": 0x25, "\x7f": 0x2A, "£": 0x30 | SHIFT, "§": 0x38 | SHIFT, "°": 0x2D | SHIFT, "²": 0x35, "µ": 0x31 | SHIFT, "à": 0x27, "ç": 0x26, "è": 0x24, "é": 0x1F, "ù": 0x34, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/fr.py
fr.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for US English Norman keyboard layout""" SHIFT = 0x80 scancodes = { "a": 0x04, "b": 0x05, "c": 0x06, "d": 0x08, "e": 0x07, "f": 0x15, "g": 0x0A, "h": 0x33, "i": 0x0E, "j": 0x1C, "k": 0x17, "l": 0x12, "m": 0x10, "n": 0x0D, "o": 0x0F, "p": 0x11, "q": 0x14, "r": 0x0C, "s": 0x16, "t": 0x09, "u": 0x18, "v": 0x19, "w": 0x1A, "x": 0x1B, "y": 0x0B, "z": 0x1D, "A": 0x04 | SHIFT, "B": 0x05 | SHIFT, "C": 0x06 | SHIFT, "D": 0x08 | SHIFT, "E": 0x07 | SHIFT, "F": 0x15 | SHIFT, "G": 0x0A | SHIFT, "H": 0x33 | SHIFT, "I": 0x0E | SHIFT, "J": 0x1C | SHIFT, "K": 0x17 | SHIFT, "L": 0x12 | SHIFT, "M": 0x10 | SHIFT, "N": 0x0D | SHIFT, "O": 0x0F | SHIFT, "P": 0x11 | SHIFT, "Q": 0x14 | SHIFT, "R": 0x0C | SHIFT, "S": 0x16 | SHIFT, "T": 0x09 | SHIFT, "U": 0x18 | SHIFT, "V": 0x19 | SHIFT, "W": 0x1A | SHIFT, "X": 0x1B | SHIFT, "Y": 0x0B | SHIFT, "Z": 0x1D | SHIFT, "0": 0x27, "1": 0x1E, "2": 0x1F, "3": 0x20, "4": 0x21, "5": 0x22, "6": 0x23, "7": 0x24, "8": 0x25, "9": 0x26, "\t": 0x2B, "\n": 0x28, "!": 0x1E | SHIFT, '"': 0x34 | SHIFT, "#": 0x20 | SHIFT, "$": 0x21 | SHIFT, "%": 0x22 | SHIFT, "&": 0x24 | SHIFT, "'": 0x34, "`": 0x35, "(": 0x26 | SHIFT, ")": 0x27 | SHIFT, "*": 0x25 | SHIFT, "+": 0x2E | SHIFT, ",": 0x36, "-": 0x2D, ".": 0x37, "/": 0x38, ":": 0x33 | SHIFT, ";": 0x13, "<": 0x36 | SHIFT, "=": 0x2E, ">": 0x37 | SHIFT, "?": 0x38 | SHIFT, "@": 0x1F | SHIFT, "[": 0x2F, "\\": 0x32, "]": 0x30, "^": 0xA3, "_": 0xAD, "{": 0x2F | SHIFT, "}": 0x30 | SHIFT, "|": 0x32 | SHIFT, "~": 0x35 | SHIFT, " ": 0x2C, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/norman.py
norman.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for IT Italian (AZERTY) keyboard layout""" SHIFT = 0x80 scancodes = { "\t": 0x2B, "\n": 0x28, " ": 0x2C, "!": 0x1E | SHIFT, '"': 0x1F | SHIFT, "#": 0x32, "$": 0x21 | SHIFT, "%": 0x22 | SHIFT, "&": 0x23 | SHIFT, "'": 0x2D, "(": 0x25 | SHIFT, ")": 0x26 | SHIFT, "*": 0x55, "+": 0x30, ",": 0x36, "-": 0x38, ".": 0x63, "/": 0x24 | SHIFT, "0": 0x27, "1": 0x1E, "2": 0x1F, "3": 0x20, "4": 0x21, "5": 0x22, "6": 0x23, "7": 0x24, "8": 0x25, "9": 0x26, ":": 0xB7, ";": 0xB6, "<": 0x64, "=": 0x27 | SHIFT, ">": 0x64 | SHIFT, "?": 0x2D | SHIFT, "@": 0x24, "A": 0x04 | SHIFT, "B": 0x05 | SHIFT, "C": 0x06 | SHIFT, "D": 0x07 | SHIFT, "E": 0x08 | SHIFT, "F": 0x09 | SHIFT, "G": 0x0A | SHIFT, "H": 0x0B | SHIFT, "I": 0x0C | SHIFT, "J": 0x0D | SHIFT, "K": 0x0E | SHIFT, "L": 0x0F | SHIFT, "M": 0x10 | SHIFT, "N": 0x11 | SHIFT, "O": 0x12 | SHIFT, "P": 0x13 | SHIFT, "Q": 0x14 | SHIFT, "R": 0x15 | SHIFT, "S": 0x16 | SHIFT, "T": 0x17 | SHIFT, "U": 0x18 | SHIFT, "V": 0x19 | SHIFT, "W": 0x1A | SHIFT, "X": 0x1B | SHIFT, "Y": 0x1C | SHIFT, "Z": 0x1D | SHIFT, "\\": 0x35, "^": 0xAE, "_": 0xB8, "`": 0x2D | SHIFT, "a": 0x04, "b": 0x05, "c": 0x06, "d": 0x07, "e": 0x08, "f": 0x09, "g": 0x0A, "h": 0x0B, "i": 0x0C, "j": 0x0D, "k": 0x0E, "l": 0x0F, "m": 0x10, "n": 0x11, "o": 0x12, "p": 0x13, "q": 0x14, "r": 0x15, "s": 0x16, "t": 0x17, "u": 0x18, "v": 0x19, "w": 0x1A, "x": 0x1B, "y": 0x1C, "z": 0x1D, "|": 0xB5, "£": 0xA0, "§": 0xB2, "°": 0xB4, "ç": 0xB3, "è": 0x2F, "é": 0x2F | SHIFT, "à": 0x34, "ì": 0x2E, "ò": 0x33, "ù": 0x31, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/it.py
it.py
# Copyright (c) 2018 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Scancode map for DE German keyboard layout""" SHIFT = 0x80 scancodes = { "a": 0x04, "b": 0x05, "c": 0x06, "d": 0x07, "e": 0x08, "f": 0x09, "g": 0x0A, "h": 0x0B, "i": 0x0C, "j": 0x0D, "k": 0x0E, "l": 0x0F, "m": 0x10, "n": 0x11, "o": 0x12, "p": 0x13, "q": 0x14, "r": 0x15, "s": 0x16, "t": 0x17, "u": 0x18, "v": 0x19, "w": 0x1A, "x": 0x1B, "y": 0x1D, "z": 0x1C, "A": 0x04 | SHIFT, "B": 0x05 | SHIFT, "C": 0x06 | SHIFT, "D": 0x07 | SHIFT, "E": 0x08 | SHIFT, "F": 0x09 | SHIFT, "G": 0x0A | SHIFT, "H": 0x0B | SHIFT, "I": 0x0C | SHIFT, "J": 0x0D | SHIFT, "K": 0x0E | SHIFT, "L": 0x0F | SHIFT, "M": 0x10 | SHIFT, "N": 0x11 | SHIFT, "O": 0x12 | SHIFT, "P": 0x13 | SHIFT, "Q": 0x14 | SHIFT, "R": 0x15 | SHIFT, "S": 0x16 | SHIFT, "T": 0x17 | SHIFT, "U": 0x18 | SHIFT, "V": 0x19 | SHIFT, "W": 0x1A | SHIFT, "X": 0x1B | SHIFT, "Y": 0x1D | SHIFT, "Z": 0x1C | SHIFT, "0": 0x27, "1": 0x1E, "2": 0x1F, "3": 0x20, "4": 0x21, "5": 0x22, "6": 0x23, "7": 0x24, "8": 0x25, "9": 0x26, "\t": 0x2B, "\n": 0x28, "!": 0x1E | SHIFT, '"': 0x1F | SHIFT, "#": 0x32, "$": 0x21 | SHIFT, "%": 0x22 | SHIFT, "&": 0x23 | SHIFT, "'": 0x32 | SHIFT, "(": 0x25 | SHIFT, ")": 0x26 | SHIFT, "*": 0x30 | SHIFT, "+": 0x30, ",": 0x36, "-": 0x38, ".": 0x37, "/": 0x24 | SHIFT, ":": 0x37 | SHIFT, ";": 0x36 | SHIFT, "<": 0x64, "=": 0x27 | SHIFT, ">": 0x64 | SHIFT, "?": 0x2D | SHIFT, "^": 0x35, "_": 0x38 | SHIFT, " ": 0x2C, "`": 0x2D | SHIFT, "§": 0x20 | SHIFT, "´": 0x2E, "Ä": 0x34 | SHIFT, "Ö": 0x33 | SHIFT, "Ü": 0x2F | SHIFT, "ß": 0x2D, "ä": 0x34, "ö": 0x33, "ü": 0x2F, }
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/scancodes/de.py
de.py
import functools import click import sys from yubikit.management import DeviceInfo from yubikit.oath import parse_b32_key from collections import OrderedDict from collections.abc import MutableMapping from cryptography.hazmat.primitives import serialization from contextlib import contextmanager from threading import Timer from enum import Enum from typing import List import logging logger = logging.getLogger(__name__) class _YkmanCommand(click.Command): def __init__(self, *args, **kwargs): connections = kwargs.pop("connections", None) if connections and not isinstance(connections, list): connections = [connections] # Single type self.connections = connections super().__init__(*args, **kwargs) def get_short_help_str(self, limit=45): help_str = super().get_short_help_str(limit) return help_str[0].lower() + help_str[1:].rstrip(".") def get_help_option(self, ctx): option = super().get_help_option(ctx) option.help = "show this message and exit" return option class _YkmanGroup(_YkmanCommand, click.Group): command_class = _YkmanCommand def add_command(self, cmd, name=None): if not isinstance(cmd, (_YkmanGroup, _YkmanCommand)): raise ValueError( f"Command {cmd} does not inherit from _YkmanGroup or _YkmanCommand" ) super().add_command(cmd, name) def list_commands(self, ctx): return sorted( self.commands, key=lambda c: (isinstance(self.commands[c], click.Group), c) ) _YkmanGroup.group_class = _YkmanGroup def click_group(*args, connections=None, **kwargs): return click.group( *args, cls=_YkmanGroup, connections=connections, **kwargs, ) def click_command(*args, connections=None, **kwargs): return click.command( *args, cls=_YkmanCommand, connections=connections, **kwargs, ) class EnumChoice(click.Choice): """ Use an enum's member names as the definition for a choice option. Enum member names MUST be all uppercase. Options are not case sensitive. Underscores in enum names are translated to dashes in the option choice. """ def __init__(self, choices_enum, hidden=[]): self.choices_names = [ v.name.replace("_", "-") for v in choices_enum if v not in hidden ] super().__init__( self.choices_names, case_sensitive=False, ) self.hidden = hidden self.choices_enum = choices_enum def convert(self, value, param, ctx): if isinstance(value, self.choices_enum): return value try: # Allow aliases self.choices = [ k.replace("_", "-") for k, v in self.choices_enum.__members__.items() if v not in self.hidden ] name = super().convert(value, param, ctx).replace("-", "_") finally: self.choices = self.choices_names return self.choices_enum[name] def click_callback(invoke_on_missing=False): def wrap(f): @functools.wraps(f) def inner(ctx, param, val): if not invoke_on_missing and not param.required and val is None: return None try: return f(ctx, param, val) except ValueError as e: ctx.fail(f'Invalid value for "{param.name}": {str(e)}') return inner return wrap @click_callback() def click_parse_format(ctx, param, val): if val == "PEM": return serialization.Encoding.PEM elif val == "DER": return serialization.Encoding.DER else: raise ValueError(val) click_force_option = click.option( "-f", "--force", is_flag=True, help="confirm the action without prompting" ) click_format_option = click.option( "-F", "--format", type=click.Choice(["PEM", "DER"], case_sensitive=False), default="PEM", show_default=True, help="encoding format", callback=click_parse_format, ) class YkmanContextObject(MutableMapping): def __init__(self): self._objects = OrderedDict() self._resolved = False def add_resolver(self, key, f): if self._resolved: f = f() self._objects[key] = f def resolve(self): if not self._resolved: self._resolved = True for k, f in self._objects.copy().items(): self._objects[k] = f() def __getitem__(self, key): self.resolve() return self._objects[key] def __setitem__(self, key, value): if not self._resolved: raise ValueError("BUG: Attempted to set item when unresolved.") self._objects[key] = value def __delitem__(self, key): del self._objects[key] def __len__(self): return len(self._objects) def __iter__(self): return iter(self._objects) def click_postpone_execution(f): @functools.wraps(f) def inner(*args, **kwargs): click.get_current_context().obj.add_resolver(str(f), lambda: f(*args, **kwargs)) return inner @click_callback() def click_parse_b32_key(ctx, param, val): return parse_b32_key(val) def click_prompt(prompt, err=True, **kwargs): """Replacement for click.prompt to better work when piping input to the command. Note that we change the default of err to be True, since that's how we typically use it. """ logger.debug(f"Input requested ({prompt})") if not sys.stdin.isatty(): # Piped from stdin, see if there is data logger.debug("TTY detected, reading line from stdin...") line = sys.stdin.readline() if line: return line.rstrip("\n") logger.debug("No data available on stdin") # No piped data, use standard prompt logger.debug("Using interactive prompt...") return click.prompt(prompt, err=err, **kwargs) def prompt_for_touch(): logger.debug("Prompting user to touch YubiKey...") try: click.echo("Touch your YubiKey...", err=True) except Exception: sys.stderr.write("Touch your YubiKey...\n") @contextmanager def prompt_timeout(timeout=0.5): timer = Timer(timeout, prompt_for_touch) try: timer.start() yield None finally: timer.cancel() class CliFail(Exception): def __init__(self, message, status=1): super().__init__(message) self.status = status def pretty_print(value, level: int = 0) -> List[str]: """Pretty-prints structured data, as that returned by get_diagnostics. Returns a list of strings which can be printed as lines. """ indent = " " * level lines = [] if isinstance(value, list): for v in value: lines.extend(pretty_print(v, level)) elif isinstance(value, dict): res = [] mlen = 0 for k, v in value.items(): if isinstance(k, Enum): k = k.name or str(k) p = pretty_print(v, level + 1) ml = len(p) > 1 or isinstance(v, (list, dict)) if not ml: mlen = max(mlen, len(k)) res.append((k, p, ml)) mlen += len(indent) + 1 for k, p, ml in res: k_line = f"{indent}{k}:".ljust(mlen) if ml: lines.append(k_line) lines.extend(p) if lines[-1] != "": lines.append("") else: lines.append(f"{k_line} {p[0].lstrip()}") elif isinstance(value, bytes): lines.append(f"{indent}{value.hex()}") else: lines.append(f"{indent}{value}") return lines def is_yk4_fips(info: DeviceInfo) -> bool: return info.version[0] == 4 and info.is_fips
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/util.py
util.py
import sys import logging """ Command line aliases to support commands which have moved. The old commands are no longer supported and will fail, but will show their replacement. """ logger = logging.getLogger(__name__) ignore = None def replace(*args): def inner(argv, alias, match_at): return argv[:match_at] + list(args) + argv[match_at + len(alias) :] return inner def oath_access_remember(argv, alias, match_at): args = ["oath", "access"] for flag in ("-c", "--clear-all"): if flag in argv: argv.remove(flag) args.extend(["forget", "--all"]) break else: for flag in ("-F", "--forget"): if flag in argv: argv.remove(flag) args.append("forget") break else: args.append("remember") argv = argv[:match_at] + args + argv[match_at + len(alias) :] return argv _aliases = ( (["config", "mode"], ignore), # Avoid match on next line (["mode"], replace("config", "mode")), (["fido", "delete"], replace("fido", "credentials", "delete")), (["fido", "list"], replace("fido", "credentials", "list")), (["fido", "set-pin"], replace("fido", "access", "change-pin")), (["fido", "unlock"], replace("fido", "access", "verify-pin")), (["piv", "change-pin"], replace("piv", "access", "change-pin")), (["piv", "change-puk"], replace("piv", "access", "change-puk")), ( ["piv", "change-management-key"], replace("piv", "access", "change-management-key"), ), (["piv", "set-pin-retries"], replace("piv", "access", "set-retries")), (["piv", "unblock-pin"], replace("piv", "access", "unblock-pin")), (["piv", "attest"], replace("piv", "keys", "attest")), (["piv", "import-key"], replace("piv", "keys", "import")), (["piv", "generate-key"], replace("piv", "keys", "generate")), (["piv", "import-certificate"], replace("piv", "certificates", "import")), (["piv", "export-certificate"], replace("piv", "certificates", "export")), (["piv", "generate-certificate"], replace("piv", "certificates", "generate")), (["piv", "delete-certificate"], replace("piv", "certificates", "delete")), (["piv", "generate-csr"], replace("piv", "certificates", "request")), (["piv", "read-object"], replace("piv", "objects", "export")), (["piv", "write-object"], replace("piv", "objects", "import")), (["piv", "set-chuid"], replace("piv", "objects", "generate", "chuid")), (["piv", "set-ccc"], replace("piv", "objects", "generate", "ccc")), (["openpgp", "set-pin-retries"], replace("openpgp", "access", "set-retries")), (["openpgp", "import-certificate"], replace("openpgp", "certificates", "import")), (["openpgp", "export-certificate"], replace("openpgp", "certificates", "export")), (["openpgp", "delete-certificate"], replace("openpgp", "certificates", "delete")), (["openpgp", "attest"], replace("openpgp", "keys", "attest")), ( ["openpgp", "import-attestation-key"], replace("openpgp", "keys", "import", "att"), ), (["openpgp", "set-touch"], replace("openpgp", "keys", "set-touch")), (["oath", "add"], replace("oath", "accounts", "add")), (["oath", "code"], replace("oath", "accounts", "code")), (["oath", "delete"], replace("oath", "accounts", "delete")), (["oath", "list"], replace("oath", "accounts", "list")), (["oath", "uri"], replace("oath", "accounts", "uri")), (["oath", "set-password"], replace("oath", "access", "change")), (["oath", "remember-password"], oath_access_remember), ) def _find_match(data, selection): ln = len(selection) for i in range(0, len(data) - ln + 1): if data[i : i + ln] == selection: return i def apply_aliases(argv): for (alias, f) in _aliases: i = _find_match(argv, alias) if i is not None: if f: argv = f(argv, alias, i) logger.exception( "This command has moved! Use ykman " + " ".join(argv[1:]) ) sys.exit(1) break # Only handle first match return argv
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/aliases.py
aliases.py
from yubikit.core import ApplicationNotAvailableError from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from yubikit.support import get_name, read_info from yubikit.logging import LOG_LEVEL from .. import __version__ from ..pcsc import list_devices as list_ccid, list_readers from ..device import scan_devices, list_all_devices from ..util import get_windows_version from ..logging import init_logging from ..diagnostics import get_diagnostics, sys_info from .util import YkmanContextObject, click_group, EnumChoice, CliFail, pretty_print from .info import info from .otp import otp from .openpgp import openpgp from .oath import oath from .piv import piv from .fido import fido from .config import config from .aliases import apply_aliases from .apdu import apdu from .script import run_script from .hsmauth import hsmauth import click import ctypes import time import sys import logging logger = logging.getLogger(__name__) CLICK_CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"], max_content_width=999) WIN_CTAP_RESTRICTED = ( sys.platform == "win32" and not bool(ctypes.windll.shell32.IsUserAnAdmin()) and get_windows_version() >= (10, 0, 18362) ) def _scan_changes(state, attempts=10): for _ in range(attempts): time.sleep(0.25) devices, new_state = scan_devices() if new_state != state: return devices, new_state raise TimeoutError("Timed out waiting for state change") def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo(f"YubiKey Manager (ykman) version: {__version__}") ctx.exit() def print_diagnostics(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo("\n".join(pretty_print(get_diagnostics()))) ctx.exit() def require_reader(connection_types, reader): if SmartCardConnection in connection_types or FidoConnection in connection_types: readers = list_ccid(reader) if len(readers) == 1: dev = readers[0] try: with dev.open_connection(SmartCardConnection) as conn: info = read_info(conn, dev.pid) return dev, info except Exception: raise CliFail("Failed to connect to YubiKey") elif len(readers) > 1: raise CliFail("Multiple external readers match name.") else: raise CliFail("No YubiKey found on external reader.") else: raise CliFail("Not a CCID command.") def require_device(connection_types, serial=None): # Find all connected devices devices, state = scan_devices() n_devs = sum(devices.values()) if serial is None: if n_devs == 0: # The device might not yet be ready, wait a bit try: devices, state = _scan_changes(state) n_devs = sum(devices.values()) except TimeoutError: raise CliFail("No YubiKey detected!") if n_devs > 1: raise CliFail( "Multiple YubiKeys detected. Use --device SERIAL to specify " "which one to use." ) # Only one connected device, check if any needed interfaces are available pid = next(iter(devices.keys())) supported = [c for c in connection_types if pid.supports_connection(c)] if WIN_CTAP_RESTRICTED and supported == [FidoConnection]: # FIDO-only command on Windows without Admin won't work. raise CliFail("FIDO access on Windows requires running as Administrator.") if not supported: interfaces = [c.usb_interface for c in connection_types] req = ", ".join(t.name or str(t) for t in interfaces) raise CliFail( f"Command requires one of the following USB interfaces " f"to be enabled: '{req}'.\n\n" "Use 'ykman config usb' to set the enabled USB interfaces." ) devs = list_all_devices(supported) if len(devs) != 1: raise CliFail("Failed to connect to YubiKey.") return devs[0] else: for _ in (0, 1): # If no match initially, wait a bit for state change. devs = list_all_devices(connection_types) for dev, nfo in devs: if nfo.serial == serial: return dev, nfo devices, state = _scan_changes(state) raise CliFail( f"Failed connecting to a YubiKey with serial: {serial}.\n" "Make sure the application has the required permissions.", ) @click_group(context_settings=CLICK_CONTEXT_SETTINGS) @click.option( "-d", "--device", type=int, metavar="SERIAL", help="specify which YubiKey to interact with by serial number", ) @click.option( "-r", "--reader", help="specify a YubiKey by smart card reader name " "(can't be used with --device or list)", metavar="NAME", default=None, ) @click.option( "-l", "--log-level", default=None, type=EnumChoice(LOG_LEVEL, hidden=[LOG_LEVEL.NOTSET]), help="enable logging at given verbosity level", ) @click.option( "--log-file", default=None, type=str, metavar="FILE", help="write log to FILE instead of printing to stderr (requires --log-level)", ) @click.option( "--diagnose", is_flag=True, callback=print_diagnostics, expose_value=False, is_eager=True, help="show diagnostics information useful for troubleshooting", ) @click.option( "-v", "--version", is_flag=True, callback=print_version, expose_value=False, is_eager=True, help="show version information about the app", ) @click.option( "--full-help", is_flag=True, expose_value=False, help="show --help output, including hidden commands", ) @click.pass_context def cli(ctx, device, log_level, log_file, reader): """ Configure your YubiKey via the command line. Examples: \b List connected YubiKeys, only output serial number: $ ykman list --serials \b Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info """ ctx.obj = YkmanContextObject() if log_level: init_logging(log_level, log_file=log_file) logger.info("\n".join(pretty_print({"System info": sys_info()}))) elif log_file: ctx.fail("--log-file requires specifying --log-level.") if reader and device: ctx.fail("--reader and --device options can't be combined.") subcmd = next(c for c in COMMANDS if c.name == ctx.invoked_subcommand) # Commands that don't directly act on a key if subcmd in (list_keys,): if device: ctx.fail("--device can't be used with this command.") if reader: ctx.fail("--reader can't be used with this command.") return # Commands which need a YubiKey to act on connections = getattr( subcmd, "connections", [SmartCardConnection, FidoConnection, OtpConnection] ) if connections: def resolve(): if connections == [FidoConnection] and WIN_CTAP_RESTRICTED: # FIDO-only command on Windows without Admin won't work. raise CliFail( "FIDO access on Windows requires running as Administrator." ) items = getattr(resolve, "items", None) if not items: if reader is not None: items = require_reader(connections, reader) else: items = require_device(connections, device) setattr(resolve, "items", items) return items ctx.obj.add_resolver("device", lambda: resolve()[0]) ctx.obj.add_resolver("pid", lambda: resolve()[0].pid) ctx.obj.add_resolver("info", lambda: resolve()[1]) @cli.command("list") @click.option( "-s", "--serials", is_flag=True, help="output only serial numbers, one per line " "(devices without serial will be omitted)", ) @click.option("-r", "--readers", is_flag=True, help="list available smart card readers") @click.pass_context def list_keys(ctx, serials, readers): """ List connected YubiKeys. """ if readers: for reader in list_readers(): click.echo(reader.name) ctx.exit() # List all attached devices pids = set() for dev, dev_info in list_all_devices(): if serials: if dev_info.serial: click.echo(dev_info.serial) else: if dev.pid is None: # Devices from list_all_devices should always have PID. raise AssertionError("PID is None") name = get_name(dev_info, dev.pid.yubikey_type) version = dev_info.version or "unknown" mode = dev.pid.name.split("_", 1)[1].replace("_", "+") click.echo( f"{name} ({version}) [{mode}]" + (f" Serial: {dev_info.serial}" if dev_info.serial else "") ) pids.add(dev.pid) # Look for FIDO devices that we can't access if not serials: devs, _ = scan_devices() for pid, count in devs.items(): if pid not in pids: for _ in range(count): name = pid.yubikey_type.value mode = pid.name.split("_", 1)[1].replace("_", "+") click.echo(f"{name} [{mode}] <access denied>") COMMANDS = ( list_keys, info, otp, openpgp, oath, piv, fido, config, apdu, run_script, hsmauth, ) for cmd in COMMANDS: cli.add_command(cmd) class _DefaultFormatter(logging.Formatter): def __init__(self, show_trace=False): self.show_trace = show_trace def format(self, record): message = f"{record.levelname}: {record.getMessage()}" if self.show_trace and record.exc_info: message += self.formatException(record.exc_info) return message def main(): # Set up default logging handler = logging.StreamHandler() handler.setLevel(logging.WARNING) formatter = _DefaultFormatter() handler.setFormatter(formatter) logging.getLogger().addHandler(handler) sys.argv = apply_aliases(sys.argv) try: # --full-help triggers --help, hidden commands will already have read it by now. sys.argv[sys.argv.index("--full-help")] = "--help" except ValueError: pass # No --full-help try: cli(obj={}) except Exception as e: status = 1 if isinstance(e, CliFail): status = e.status msg = e.args[0] elif isinstance(e, ApplicationNotAvailableError): msg = ( "The functionality required for this command is not enabled or not " "available on this YubiKey." ) elif isinstance(e, ValueError): msg = f"{e}" else: msg = "An unexpected error has occured" formatter.show_trace = True logger.exception(msg) sys.exit(status) if __name__ == "__main__": main()
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/__main__.py
__main__.py
import click import logging from .util import ( CliFail, click_force_option, click_postpone_execution, click_callback, click_parse_b32_key, click_prompt, click_group, prompt_for_touch, prompt_timeout, EnumChoice, is_yk4_fips, ) from yubikit.core.smartcard import ApduError, SW, SmartCardConnection from yubikit.oath import ( OathSession, CredentialData, OATH_TYPE, HASH_ALGORITHM, parse_b32_key, _format_cred_id, ) from ..oath import is_steam, calculate_steam, is_hidden from ..settings import AppData logger = logging.getLogger(__name__) @click_group(connections=[SmartCardConnection]) @click.pass_context @click_postpone_execution def oath(ctx): """ Manage the OATH application. Examples: \b Generate codes for accounts starting with 'yubi': $ ykman oath accounts code yubi \b Add an account with the secret key f5up4ub3dw and the name yubico, which requires touch: $ ykman oath accounts add yubico f5up4ub3dw --touch \b Set a password for the OATH application: $ ykman oath access change-password """ dev = ctx.obj["device"] conn = dev.open_connection(SmartCardConnection) ctx.call_on_close(conn.close) ctx.obj["session"] = OathSession(conn) ctx.obj["oath_keys"] = AppData("oath_keys") @oath.command() @click.pass_context def info(ctx): """ Display general status of the OATH application. """ session = ctx.obj["session"] version = session.version click.echo(f"OATH version: {version[0]}.{version[1]}.{version[2]}") click.echo("Password protection: " + ("enabled" if session.locked else "disabled")) keys = ctx.obj["oath_keys"] if session.locked and session.device_id in keys: click.echo("The password for this YubiKey is remembered by ykman.") if is_yk4_fips(ctx.obj["info"]): click.echo(f"FIPS Approved Mode: {'Yes' if session.locked else 'No'}") @oath.command() @click.pass_context @click_force_option def reset(ctx, force): """ Reset all OATH data. This action will delete all accounts and restore factory settings for the OATH application on the YubiKey. """ force or click.confirm( "WARNING! This will delete all stored OATH accounts and restore factory " "settings. Proceed?", abort=True, err=True, ) session = ctx.obj["session"] click.echo("Resetting OATH data...") old_id = session.device_id session.reset() keys = ctx.obj["oath_keys"] if old_id in keys: del keys[old_id] keys.write() logger.info("Deleted remembered access key") click.echo("Success! All OATH accounts have been deleted from the YubiKey.") click_password_option = click.option( "-p", "--password", help="the password to unlock the YubiKey" ) click_remember_option = click.option( "-r", "--remember", is_flag=True, help="remember the password on this machine", ) def _validate(ctx, key, remember): session = ctx.obj["session"] keys = ctx.obj["oath_keys"] session.validate(key) if remember: keys.put_secret(session.device_id, key.hex()) keys.write() logger.info("Access key remembered") click.echo("Password remembered.") def _init_session(ctx, password, remember, prompt="Enter the password"): session = ctx.obj["session"] keys = ctx.obj["oath_keys"] device_id = session.device_id if session.locked: try: # Use password, if given as argument if password: logger.debug("Access key required, using provided password") key = session.derive_key(password) _validate(ctx, key, remember) return # Use stored key, if available if device_id in keys: logger.debug("Access key required, using remembered key") try: key = bytes.fromhex(keys.get_secret(device_id)) _validate(ctx, key, False) return except ApduError as e: # Delete wrong key and fall through to prompt if e.sw == SW.INCORRECT_PARAMETERS: logger.debug("Remembered key incorrect, deleting key") del keys[device_id] keys.write() except Exception as e: # Other error, fall though to prompt logger.warning("Error authenticating", exc_info=e) # Prompt for password password = click_prompt(prompt, hide_input=True) key = session.derive_key(password) _validate(ctx, key, remember) except ApduError: raise CliFail("Authentication to the YubiKey failed. Wrong password?") elif password: raise CliFail("Password provided, but no password is set.") @oath.group() def access(): """Manage password protection for OATH.""" @access.command() @click.pass_context @click_password_option @click.option( "-c", "--clear", is_flag=True, help="remove the current password", ) @click.option("-n", "--new-password", help="provide a new password as an argument") @click_remember_option def change(ctx, password, clear, new_password, remember): """ Change the password used to protect OATH accounts. Allows you to set or change a password that will be required to access the OATH accounts stored on the YubiKey. """ if clear and new_password: ctx.fail("--clear cannot be combined with --new-password.") _init_session(ctx, password, False, prompt="Enter the current password") session = ctx.obj["session"] keys = ctx.obj["oath_keys"] device_id = session.device_id if clear: session.unset_key() if device_id in keys: del keys[device_id] keys.write() logger.info("Deleted remembered access key") click.echo("Password cleared from YubiKey.") else: if remember: try: keys.ensure_unlocked() except ValueError: raise CliFail( "Failed to remember password, the keyring is locked or unavailable." ) if not new_password: new_password = click_prompt( "Enter the new password", hide_input=True, confirmation_prompt=True ) key = session.derive_key(new_password) if remember: keys.put_secret(device_id, key.hex()) keys.write() click.echo("Password remembered.") elif device_id in keys: del keys[device_id] keys.write() session.set_key(key) click.echo("Password updated.") @access.command() @click.pass_context @click_password_option def remember(ctx, password): """ Store the YubiKeys password on this computer to avoid having to enter it on each use. """ session = ctx.obj["session"] device_id = session.device_id keys = ctx.obj["oath_keys"] if not session.locked: if device_id in keys: del keys[session.device_id] keys.write() logger.info("Deleted remembered access key") click.echo("This YubiKey is not password protected.") else: try: keys.ensure_unlocked() except ValueError: raise CliFail( "Failed to remember password, the keyring is locked or unavailable." ) if not password: password = click_prompt("Enter the password", hide_input=True) key = session.derive_key(password) try: _validate(ctx, key, True) except Exception: raise CliFail("Authentication to the YubiKey failed. Wrong password?") def _clear_all_passwords(ctx, param, value): if not value or ctx.resilient_parsing: return keys = AppData("oath_keys") if keys: keys.clear() keys.write() click.echo("All passwords have been forgotten.") ctx.exit() @access.command() @click.pass_context @click.option( "-a", "--all", is_flag=True, is_eager=True, expose_value=False, callback=_clear_all_passwords, help="remove all stored passwords", ) def forget(ctx): """ Remove a stored password from this computer. """ session = ctx.obj["session"] device_id = session.device_id keys = ctx.obj["oath_keys"] if device_id in keys: del keys[session.device_id] keys.write() logger.info("Deleted remembered access key") click.echo("Password forgotten.") else: click.echo("No password stored for this YubiKey.") click_touch_option = click.option( "-t", "--touch", is_flag=True, help="require touch on YubiKey to generate code" ) click_show_hidden_option = click.option( "-H", "--show-hidden", is_flag=True, help="include hidden accounts" ) def _string_id(credential): return credential.id.decode("utf-8") def _error_multiple_hits(ctx, hits): click.echo( "Error: Multiple matches, please make the query more specific.", err=True ) click.echo("", err=True) for cred in hits: click.echo(_string_id(cred), err=True) ctx.exit(1) def _search(creds, query, show_hidden): hits = [] for c in creds: cred_id = _string_id(c) if not show_hidden and is_hidden(c): continue if cred_id == query: return [c] if query.lower() in cred_id.lower(): hits.append(c) return hits @oath.group() def accounts(): """Manage and use OATH accounts.""" @accounts.command() @click.argument("name") @click.argument("secret", callback=click_parse_b32_key, required=False) @click.option( "-o", "--oath-type", type=EnumChoice(OATH_TYPE), default=OATH_TYPE.TOTP.name, help="time-based (TOTP) or counter-based (HOTP) account", show_default=True, ) @click.option( "-d", "--digits", type=click.Choice(["6", "7", "8"]), default="6", help="number of digits in generated code", show_default=True, ) @click.option( "-a", "--algorithm", type=EnumChoice(HASH_ALGORITHM), default=HASH_ALGORITHM.SHA1.name, show_default=True, help="algorithm to use for code generation", ) @click.option( "-c", "--counter", type=click.INT, default=0, help="initial counter value for HOTP accounts", ) @click.option("-i", "--issuer", help="issuer of the account (optional)") @click.option( "-P", "--period", help="number of seconds a TOTP code is valid", default=30, show_default=True, ) @click_touch_option @click_force_option @click_password_option @click_remember_option @click.pass_context def add( ctx, secret, name, issuer, period, oath_type, digits, touch, algorithm, counter, force, password, remember, ): """ Add a new account. This will add a new OATH account to the YubiKey. \b NAME human readable name of the account, such as a username or e-mail address SECRET base32-encoded secret/key value provided by the server """ digits = int(digits) if not secret: while True: secret = click_prompt("Enter a secret key (base32)") try: secret = parse_b32_key(secret) break except Exception as e: click.echo(e) _init_session(ctx, password, remember) _add_cred( ctx, CredentialData( name, oath_type, algorithm, secret, digits, period, counter, issuer ), touch, force, ) @click_callback() def click_parse_uri(ctx, param, val): try: return CredentialData.parse_uri(val) except ValueError: raise click.BadParameter("URI seems to have the wrong format.") @accounts.command() @click.argument("data", callback=click_parse_uri, required=False, metavar="URI") @click_touch_option @click_force_option @click_password_option @click_remember_option @click.pass_context def uri(ctx, data, touch, force, password, remember): """ Add a new account from an otpauth:// URI. Use a URI to add a new account to the YubiKey. """ if not data: while True: uri = click_prompt("Enter an OATH URI (otpauth://)") try: data = CredentialData.parse_uri(uri) break except Exception as e: click.echo(e) # Steam is a special case where we allow the otpauth # URI to contain a 'digits' value of '5'. if data.digits == 5 and is_steam(data): data.digits = 6 _init_session(ctx, password, remember) _add_cred(ctx, data, touch, force) def _add_cred(ctx, data, touch, force): session = ctx.obj["session"] version = session.version if not (0 < len(data.name) <= 64): ctx.fail("Name must be between 1 and 64 bytes.") if len(data.secret) < 2: ctx.fail("Secret must be at least 2 bytes.") if touch and version < (4, 2, 6): raise CliFail("Require touch is not supported on this YubiKey.") if data.counter and data.oath_type != OATH_TYPE.HOTP: ctx.fail("Counter only supported for HOTP accounts.") if data.hash_algorithm == HASH_ALGORITHM.SHA512 and ( version < (4, 3, 1) or is_yk4_fips(ctx.obj["info"]) ): raise CliFail("Algorithm SHA512 not supported on this YubiKey.") creds = session.list_credentials() cred_id = data.get_id() if not force and any(cred.id == cred_id for cred in creds): click.confirm( f"An account called {data.name} already exists on this YubiKey." " Do you want to overwrite it?", abort=True, err=True, ) firmware_overwrite_issue = (4, 0, 0) < version < (4, 3, 5) cred_is_subset = any( (cred.id.startswith(cred_id) and cred.id != cred_id) for cred in creds ) # YK4 has an issue with credential overwrite in firmware versions < 4.3.5 if firmware_overwrite_issue and cred_is_subset: raise CliFail("Choose a name that is not a subset of an existing account.") try: session.put_credential(data, touch) except ApduError as e: if e.sw == SW.NO_SPACE: raise CliFail("No space left on the YubiKey for OATH accounts.") elif e.sw == SW.COMMAND_ABORTED: # Some NEOs do not use the NO_SPACE error. raise CliFail("The command failed. Is there enough space on the YubiKey?") else: raise @accounts.command() @click_show_hidden_option @click.pass_context @click.option("-o", "--oath-type", is_flag=True, help="display the OATH type") @click.option("-P", "--period", is_flag=True, help="display the period") @click_password_option @click_remember_option def list(ctx, show_hidden, oath_type, period, password, remember): """ List all accounts. List all accounts stored on the YubiKey. """ _init_session(ctx, password, remember) session = ctx.obj["session"] creds = [ cred for cred in session.list_credentials() if show_hidden or not is_hidden(cred) ] creds.sort() for cred in creds: click.echo(_string_id(cred), nl=False) if oath_type: click.echo(f", {cred.oath_type.name}", nl=False) if period: click.echo(f", {cred.period}", nl=False) click.echo() @accounts.command() @click_show_hidden_option @click.pass_context @click.argument("query", required=False, default="") @click.option( "-s", "--single", is_flag=True, help="ensure only a single match, and output only the code", ) @click_password_option @click_remember_option def code(ctx, show_hidden, query, single, password, remember): """ Generate codes. Generate codes from OATH accounts stored on the YubiKey. Provide a query string to match one or more specific accounts. Accounts of type HOTP, or those that require touch, requre a single match to be triggered. """ _init_session(ctx, password, remember) session = ctx.obj["session"] entries = session.calculate_all() creds = _search(entries.keys(), query, show_hidden) if len(creds) == 1: cred = creds[0] code = entries[cred] if cred.touch_required: prompt_for_touch() try: if cred.oath_type == OATH_TYPE.HOTP: with prompt_timeout(): # HOTP might require touch, we don't know. # Assume yes after 500ms. code = session.calculate_code(cred) elif code is None: code = session.calculate_code(cred) except ApduError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: raise CliFail("Touch account timed out!") entries[cred] = code elif single and len(creds) > 1: _error_multiple_hits(ctx, creds) elif single and len(creds) == 0: raise CliFail("No matching account found.") if single and creds: if is_steam(cred): click.echo(calculate_steam(session, cred)) else: click.echo(code.value) else: outputs = [] for cred in sorted(creds): code = entries[cred] if code: if is_steam(cred): code = calculate_steam(session, cred) else: code = code.value elif cred.touch_required: code = "[Requires Touch]" elif cred.oath_type == OATH_TYPE.HOTP: code = "[HOTP Account]" else: code = "" outputs.append((_string_id(cred), code)) longest_name = max(len(n) for (n, c) in outputs) if outputs else 0 longest_code = max(len(c) for (n, c) in outputs) if outputs else 0 format_str = "{:<%d} {:>%d}" % (longest_name, longest_code) for name, result in outputs: click.echo(format_str.format(name, result)) @accounts.command() @click.pass_context @click.argument("query") @click.argument("name") @click.option("-f", "--force", is_flag=True, help="confirm rename without prompting") @click_password_option @click_remember_option def rename(ctx, query, name, force, password, remember): """ Rename an account (requires YubiKey 5.3 or later). \b QUERY a query to match a single account (as shown in "list") NAME the name of the account (use "<issuer>:<name>" to specify issuer) """ _init_session(ctx, password, remember) session = ctx.obj["session"] creds = session.list_credentials() hits = _search(creds, query, True) if len(hits) == 0: click.echo("No matches, nothing to be done.") elif len(hits) == 1: cred = hits[0] if ":" in name: issuer, name = name.split(":", 1) else: issuer = None new_id = _format_cred_id(issuer, name, cred.oath_type, cred.period) if any(cred.id == new_id for cred in creds): raise CliFail( f"Another account with ID {new_id.decode()} " "already exists on this YubiKey." ) if force or ( click.confirm( f"Rename account: {_string_id(cred)} ?", default=False, err=True, ) ): session.rename_credential(cred.id, name, issuer) click.echo(f"Renamed {_string_id(cred)} to {new_id.decode()}.") else: click.echo("Rename aborted by user.") else: _error_multiple_hits(ctx, hits) @accounts.command() @click.pass_context @click.argument("query") @click.option("-f", "--force", is_flag=True, help="confirm deletion without prompting") @click_password_option @click_remember_option def delete(ctx, query, force, password, remember): """ Delete an account. Delete an account from the YubiKey. \b QUERY a query to match a single account (as shown in "list") """ _init_session(ctx, password, remember) session = ctx.obj["session"] creds = session.list_credentials() hits = _search(creds, query, True) if len(hits) == 0: click.echo("No matches, nothing to be done.") elif len(hits) == 1: cred = hits[0] if force or ( click.confirm( f"Delete account: {_string_id(cred)} ?", default=False, err=True, ) ): session.delete_credential(cred.id) click.echo(f"Deleted {_string_id(cred)}.") else: click.echo("Deletion aborted by user.") else: _error_multiple_hits(ctx, hits)
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/oath.py
oath.py
from fido2.ctap import CtapError from fido2.ctap1 import ApduError from fido2.ctap2 import ( Ctap2, ClientPin, CredentialManagement, FPBioEnrollment, CaptureError, ) from fido2.pcsc import CtapPcscDevice from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SW from time import sleep from .util import ( click_postpone_execution, click_prompt, click_force_option, click_group, prompt_timeout, is_yk4_fips, ) from .util import CliFail from ..fido import is_in_fips_mode, fips_reset, fips_change_pin, fips_verify_pin from ..hid import list_ctap_devices from ..pcsc import list_devices as list_ccid from smartcard.Exceptions import NoCardException, CardConnectionException from typing import Optional, Sequence, List import io import csv as _csv import click import logging logger = logging.getLogger(__name__) FIPS_PIN_MIN_LENGTH = 6 PIN_MIN_LENGTH = 4 @click_group(connections=[FidoConnection]) @click.pass_context @click_postpone_execution def fido(ctx): """ Manage the FIDO applications. Examples: \b Reset the FIDO (FIDO2 and U2F) applications: $ ykman fido reset \b Change the FIDO2 PIN from 123456 to 654321: $ ykman fido access change-pin --pin 123456 --new-pin 654321 """ dev = ctx.obj["device"] conn = dev.open_connection(FidoConnection) ctx.call_on_close(conn.close) ctx.obj["conn"] = conn try: ctx.obj["ctap2"] = Ctap2(conn) except (ValueError, CtapError): logger.info("FIDO device does not support CTAP2", exc_info=True) @fido.command() @click.pass_context def info(ctx): """ Display general status of the FIDO2 application. """ conn = ctx.obj["conn"] ctap2 = ctx.obj.get("ctap2") if is_yk4_fips(ctx.obj["info"]): click.echo("FIPS Approved Mode: " + ("Yes" if is_in_fips_mode(conn) else "No")) elif ctap2: client_pin = ClientPin(ctap2) # N.B. All YubiKeys with CTAP2 support PIN. if ctap2.info.options["clientPin"]: if ctap2.info.force_pin_change: click.echo( "NOTE: The FIDO PID is disabled and must be changed before it can " "be used!" ) pin_retries, power_cycle = client_pin.get_pin_retries() if pin_retries: click.echo(f"PIN is set, with {pin_retries} attempt(s) remaining.") if power_cycle: click.echo( "PIN is temporarily blocked. " "Remove and re-insert the YubiKey to unblock." ) else: click.echo("PIN is set, but has been blocked.") else: click.echo("PIN is not set.") bio_enroll = ctap2.info.options.get("bioEnroll") if bio_enroll: uv_retries = client_pin.get_uv_retries() if uv_retries: click.echo( f"Fingerprints registered, with {uv_retries} attempt(s) " "remaining." ) else: click.echo( "Fingerprints registered, but blocked until PIN is verified." ) elif bio_enroll is False: click.echo("No fingerprints have been registered.") always_uv = ctap2.info.options.get("alwaysUv") if always_uv is not None: click.echo( "Always Require User Verification is turned " + ("on." if always_uv else "off.") ) else: click.echo("PIN is not supported.") @fido.command("reset") @click_force_option @click.pass_context def reset(ctx, force): """ Reset all FIDO applications. This action will wipe all FIDO credentials, including FIDO U2F credentials, on the YubiKey and remove the PIN code. The reset must be triggered immediately after the YubiKey is inserted, and requires a touch on the YubiKey. """ conn = ctx.obj["conn"] if isinstance(conn, CtapPcscDevice): # NFC readers = list_ccid(conn._name) if not readers or readers[0].reader.name != conn._name: raise CliFail("Unable to isolate NFC reader.") dev = readers[0] logger.debug(f"use: {dev}") is_fips = False def prompt_re_insert(): click.echo( "Remove and re-place your YubiKey on the NFC reader to perform the " "reset..." ) removed = False while True: sleep(0.5) try: with dev.open_connection(FidoConnection): if removed: sleep(1.0) # Wait for the device to settle break except CardConnectionException: pass # Expected, ignore except NoCardException: removed = True return dev.open_connection(FidoConnection) else: # USB n_keys = len(list_ctap_devices()) if n_keys > 1: raise CliFail("Only one YubiKey can be connected to perform a reset.") is_fips = is_yk4_fips(ctx.obj["info"]) ctap2 = ctx.obj.get("ctap2") if not is_fips and not ctap2: raise CliFail("This YubiKey does not support FIDO reset.") def prompt_re_insert(): click.echo("Remove and re-insert your YubiKey to perform the reset...") removed = False while True: sleep(0.5) keys = list_ctap_devices() if not keys: removed = True if removed and len(keys) == 1: return keys[0].open_connection(FidoConnection) if not force: click.confirm( "WARNING! This will delete all FIDO credentials, including FIDO U2F " "credentials, and restore factory settings. Proceed?", err=True, abort=True, ) if is_fips: destroy_input = click_prompt( "WARNING! This is a YubiKey FIPS device. This command will also " "overwrite the U2F attestation key; this action cannot be undone and " "this YubiKey will no longer be a FIPS compliant device.\n" 'To proceed, please enter the text "OVERWRITE"', default="", show_default=False, ) if destroy_input != "OVERWRITE": raise CliFail("Reset aborted by user.") conn = prompt_re_insert() try: with prompt_timeout(): if is_fips: fips_reset(conn) else: Ctap2(conn).reset() logger.info("FIDO application data reset") except CtapError as e: if e.code == CtapError.ERR.ACTION_TIMEOUT: raise CliFail( "Reset failed. You need to touch your YubiKey to confirm the reset." ) elif e.code in (CtapError.ERR.NOT_ALLOWED, CtapError.ERR.PIN_AUTH_BLOCKED): raise CliFail( "Reset failed. Reset must be triggered within 5 seconds after the " "YubiKey is inserted." ) else: raise CliFail(f"Reset failed: {e.code.name}") except ApduError as e: # From fips_reset if e.code == SW.COMMAND_NOT_ALLOWED: raise CliFail( "Reset failed. Reset must be triggered within 5 seconds after the " "YubiKey is inserted." ) else: raise CliFail("Reset failed.") except Exception: raise CliFail("Reset failed.") def _fail_pin_error(ctx, e, other="%s"): if e.code == CtapError.ERR.PIN_INVALID: raise CliFail("Wrong PIN.") elif e.code == CtapError.ERR.PIN_AUTH_BLOCKED: raise CliFail( "PIN authentication is currently blocked. " "Remove and re-insert the YubiKey." ) elif e.code == CtapError.ERR.PIN_BLOCKED: raise CliFail("PIN is blocked.") else: raise CliFail(other % e.code) @fido.group("access") def access(): """ Manage the PIN for FIDO. """ @access.command("change-pin") @click.pass_context @click.option("-P", "--pin", help="current PIN code") @click.option("-n", "--new-pin", help="a new PIN") @click.option( "-u", "--u2f", is_flag=True, help="set FIDO U2F PIN instead of FIDO2 PIN (YubiKey 4 FIPS only)", ) def change_pin(ctx, pin, new_pin, u2f): """ Set or change the PIN code. The FIDO2 PIN must be at least 4 characters long, and supports any type of alphanumeric characters. On YubiKey FIPS, a PIN can be set for FIDO U2F. That PIN must be at least 6 characters long. """ is_fips = is_yk4_fips(ctx.obj["info"]) if is_fips and not u2f: raise CliFail( "This is a YubiKey FIPS. To set the U2F PIN, pass the --u2f option." ) if u2f and not is_fips: raise CliFail( "This is not a YubiKey 4 FIPS, and therefore does not support a U2F PIN. " "To set the FIDO2 PIN, remove the --u2f option." ) if is_fips: conn = ctx.obj["conn"] else: ctap2 = ctx.obj.get("ctap2") if not ctap2: raise CliFail("PIN is not supported on this YubiKey.") client_pin = ClientPin(ctap2) def prompt_new_pin(): return click_prompt( "Enter your new PIN", hide_input=True, confirmation_prompt=True, ) def change_pin(pin, new_pin): if pin is not None: _fail_if_not_valid_pin(ctx, pin, is_fips) try: if is_fips: try: # Failing this with empty current PIN does not cost a retry fips_change_pin(conn, pin or "", new_pin) except ApduError as e: if e.code == SW.WRONG_LENGTH: pin = _prompt_current_pin() _fail_if_not_valid_pin(ctx, pin, is_fips) fips_change_pin(conn, pin, new_pin) else: raise else: client_pin.change_pin(pin, new_pin) except CtapError as e: if e.code == CtapError.ERR.PIN_POLICY_VIOLATION: raise CliFail("New PIN doesn't meet policy requirements.") else: _fail_pin_error(ctx, e, "Failed to change PIN: %s") except ApduError as e: if e.code == SW.VERIFY_FAIL_NO_RETRY: raise CliFail("Wrong PIN.") elif e.code == SW.AUTH_METHOD_BLOCKED: raise CliFail("PIN is blocked.") else: raise CliFail(f"Failed to change PIN: SW={e.code:04x}") def set_pin(new_pin): _fail_if_not_valid_pin(ctx, new_pin, is_fips) try: client_pin.set_pin(new_pin) except CtapError as e: if e.code == CtapError.ERR.PIN_POLICY_VIOLATION: raise CliFail("New PIN doesn't meet policy requirements.") else: raise CliFail(f"Failed to set PIN: {e.code}") if not is_fips: if ctap2.info.options.get("clientPin"): if not pin: pin = _prompt_current_pin() else: if pin: raise CliFail("There is no current PIN set. Use --new-pin to set one.") if not new_pin: new_pin = prompt_new_pin() if is_fips: _fail_if_not_valid_pin(ctx, new_pin, is_fips) change_pin(pin, new_pin) else: min_len = ctap2.info.min_pin_length if len(new_pin) < min_len: raise CliFail("New PIN is too short. Minimum length: {min_len}") if ctap2.info.options.get("clientPin"): change_pin(pin, new_pin) else: set_pin(new_pin) logger.info("FIDO PIN updated") def _require_pin(ctx, pin, feature="This feature"): ctap2 = ctx.obj.get("ctap2") if not ctap2: raise CliFail(f"{feature} is not supported on this YubiKey.") if not ctap2.info.options.get("clientPin"): raise CliFail(f"{feature} requires having a PIN. Set a PIN first.") if ctap2.info.force_pin_change: raise CliFail("The FIDO PIN is blocked. Change the PIN first.") if pin is None: pin = _prompt_current_pin(prompt="Enter your PIN") return pin @access.command("verify-pin") @click.pass_context @click.option("-P", "--pin", help="current PIN code") def verify(ctx, pin): """ Verify the FIDO PIN against a YubiKey. For YubiKeys supporting FIDO2 this will reset the "retries" counter of the PIN. For YubiKey FIPS this will unlock the session, allowing U2F registration. """ ctap2 = ctx.obj.get("ctap2") if ctap2: pin = _require_pin(ctx, pin) client_pin = ClientPin(ctap2) try: # Get a PIN token to verify the PIN. client_pin.get_pin_token( pin, ClientPin.PERMISSION.GET_ASSERTION, "ykman.example.com" ) except CtapError as e: raise CliFail(f"PIN verification failed: {e}") elif is_yk4_fips(ctx.obj["info"]): _fail_if_not_valid_pin(ctx, pin, True) try: fips_verify_pin(ctx.obj["conn"], pin) except ApduError as e: if e.code == SW.VERIFY_FAIL_NO_RETRY: raise CliFail("Wrong PIN.") elif e.code == SW.AUTH_METHOD_BLOCKED: raise CliFail("PIN is blocked.") elif e.code == SW.COMMAND_NOT_ALLOWED: raise CliFail("PIN is not set.") else: raise CliFail(f"PIN verification failed: {e.code.name}") else: raise CliFail("This YubiKey does not support a FIDO PIN.") click.echo("PIN verified.") def _prompt_current_pin(prompt="Enter your current PIN"): return click_prompt(prompt, hide_input=True) def _fail_if_not_valid_pin(ctx, pin=None, is_fips=False): min_length = FIPS_PIN_MIN_LENGTH if is_fips else PIN_MIN_LENGTH if not pin or len(pin) < min_length: ctx.fail(f"PIN must be over {min_length} characters long") def _gen_creds(credman): data = credman.get_metadata() if data.get(CredentialManagement.RESULT.EXISTING_CRED_COUNT) == 0: return # No credentials for rp in credman.enumerate_rps(): for cred in credman.enumerate_creds(rp[CredentialManagement.RESULT.RP_ID_HASH]): yield ( rp[CredentialManagement.RESULT.RP]["id"], cred[CredentialManagement.RESULT.CREDENTIAL_ID], cred[CredentialManagement.RESULT.USER]["id"], cred[CredentialManagement.RESULT.USER].get("name", ""), cred[CredentialManagement.RESULT.USER].get("displayName", ""), ) def _format_table(headings: Sequence[str], rows: List[Sequence[str]]) -> str: all_rows = [headings] + rows padded_rows = [["" for cell in row] for row in all_rows] max_cols = max(len(row) for row in all_rows) for c in range(max_cols): max_width = max(len(row[c]) for row in all_rows if len(row) > c) for r in range(len(all_rows)): if c < len(all_rows[r]): padded_rows[r][c] = all_rows[r][c] + ( " " * (max_width - len(all_rows[r][c])) ) return "\n".join(" ".join(row) for row in padded_rows) def _format_cred(rp_id, user_id, user_name): return f"{rp_id} {user_id.hex()} {user_name}" @fido.group("credentials") def creds(): """ Manage discoverable (resident) credentials. This command lets you manage credentials stored on your YubiKey. Credential management is only available when a FIDO PIN is set on the YubiKey. \b Examples: \b List credentials (providing PIN via argument): $ ykman fido credentials list --pin 123456 \b Delete a credential (ID shown in "list" output, PIN will be prompted for): $ ykman fido credentials delete da7fdc """ def _init_credman(ctx, pin): pin = _require_pin(ctx, pin, "Credential Management") ctap2 = ctx.obj.get("ctap2") client_pin = ClientPin(ctap2) try: token = client_pin.get_pin_token(pin, ClientPin.PERMISSION.CREDENTIAL_MGMT) except CtapError as e: _fail_pin_error(ctx, e, "PIN error: %s") return CredentialManagement(ctap2, client_pin.protocol, token) @creds.command("list") @click.pass_context @click.option("-P", "--pin", help="PIN code") @click.option( "-c", "--csv", is_flag=True, help="output full credential information as CSV", ) def creds_list(ctx, pin, csv): """ List credentials. Shows a list of credentials stored on the YubiKey. The --csv flag will output more complete information about each credential, formatted as a CSV (comma separated values). """ credman = _init_credman(ctx, pin) creds = list(_gen_creds(credman)) if csv: buf = io.StringIO() writer = _csv.writer(buf) writer.writerow( ["credential_id", "rp_id", "user_name", "user_display_name", "user_id"] ) writer.writerows( [cred_id["id"].hex(), rp_id, user_name, display_name, user_id.hex()] for rp_id, cred_id, user_id, user_name, display_name in creds ) click.echo(buf.getvalue()) else: ln = 4 while len(set(c[1]["id"][:ln] for c in creds)) < len(creds): ln += 1 click.echo( _format_table( ["Credential ID", "RP ID", "Username", "Display name"], [ (cred_id["id"][:ln].hex() + "...", rp_id, user_name, display_name) for rp_id, cred_id, _, user_name, display_name in creds ], ) ) @creds.command("delete") @click.pass_context @click.argument("credential_id") @click.option("-P", "--pin", help="PIN code") @click.option("-f", "--force", is_flag=True, help="confirm deletion without prompting") def creds_delete(ctx, credential_id, pin, force): """ Delete a credential. List stored credential IDs using the "list" subcommand. \b CREDENTIAL_ID a unique substring match of a Credential ID """ credman = _init_credman(ctx, pin) credential_id = credential_id.rstrip(".").lower() hits = [ (rp_id, cred_id, user_name, display_name) for (rp_id, cred_id, _, user_name, display_name) in _gen_creds(credman) if cred_id["id"].hex().startswith(credential_id) ] if len(hits) == 0: raise CliFail("No matches, nothing to be done.") elif len(hits) == 1: (rp_id, cred_id, user_name, display_name) = hits[0] if force or click.confirm( f"Delete {rp_id} {user_name} {display_name} ({cred_id['id'].hex()})?" ): try: credman.delete_cred(cred_id) logger.info("Credential deleted") except CtapError: raise CliFail("Failed to delete credential.") else: raise CliFail("Multiple matches, make the credential ID more specific.") @fido.group("fingerprints") def bio(): """ Manage fingerprints. Requires a YubiKey with fingerprint sensor. Fingerprint management is only available when a FIDO PIN is set on the YubiKey. \b Examples: \b Register a new fingerprint (providing PIN via argument): $ ykman fido fingerprints add "Left thumb" --pin 123456 \b List already stored fingerprints (providing PIN via argument): $ ykman fido fingerprints list --pin 123456 \b Delete a stored fingerprint with ID "f691" (PIN will be prompted for): $ ykman fido fingerprints delete f691 """ def _init_bio(ctx, pin): ctap2 = ctx.obj.get("ctap2") if not ctap2 or "bioEnroll" not in ctap2.info.options: raise CliFail("Biometrics is not supported on this YubiKey.") pin = _require_pin(ctx, pin, "Biometrics") client_pin = ClientPin(ctap2) try: token = client_pin.get_pin_token(pin, ClientPin.PERMISSION.BIO_ENROLL) except CtapError as e: _fail_pin_error(ctx, e, "PIN error: %s") return FPBioEnrollment(ctap2, client_pin.protocol, token) def _format_fp(template_id, name): return f"{template_id.hex()}{f' ({name})' if name else ''}" @bio.command("list") @click.pass_context @click.option("-P", "--pin", help="PIN code") def bio_list(ctx, pin): """ List registered fingerprints. Lists fingerprints by ID and (if available) label. """ bio = _init_bio(ctx, pin) for t_id, name in bio.enumerate_enrollments().items(): click.echo(f"ID: {_format_fp(t_id, name)}") @bio.command("add") @click.pass_context @click.argument("name") @click.option("-P", "--pin", help="PIN code") def bio_enroll(ctx, name, pin): """ Add a new fingerprint. \b NAME a short readable name for the fingerprint (eg. "Left thumb") """ if len(name.encode()) > 15: ctx.fail("Fingerprint name must be a maximum of 15 characters") bio = _init_bio(ctx, pin) enroller = bio.enroll() template_id = None while template_id is None: click.echo("Place your finger against the sensor now...") try: template_id = enroller.capture() remaining = enroller.remaining if remaining: click.echo(f"{remaining} more scans needed.") except CaptureError as e: logger.debug(f"Capture error: {e.code}") click.echo("Capture failed. Re-center your finger, and try again.") except CtapError as e: if e.code == CtapError.ERR.FP_DATABASE_FULL: raise CliFail( "Fingerprint storage full. " "Remove some fingerprints before adding new ones." ) elif e.code == CtapError.ERR.USER_ACTION_TIMEOUT: raise CliFail("Failed to add fingerprint due to user inactivity.") raise CliFail(f"Failed to add fingerprint: {e.code.name}") logger.info("Fingerprint template registered") click.echo("Capture complete.") bio.set_name(template_id, name) logger.info("Fingerprint template name set") @bio.command("rename") @click.pass_context @click.argument("template_id", metavar="ID") @click.argument("name") @click.option("-P", "--pin", help="PIN code") def bio_rename(ctx, template_id, name, pin): """ Set the label for a fingerprint. \b ID the ID of the fingerprint to rename (as shown in "list") NAME a short readable name for the fingerprint (eg. "Left thumb") """ if len(name.encode()) >= 16: ctx.fail("Fingerprint name must be a maximum of 15 bytes") bio = _init_bio(ctx, pin) enrollments = bio.enumerate_enrollments() key = bytes.fromhex(template_id) if key not in enrollments: raise CliFail(f"No fingerprint matching ID={template_id}.") bio.set_name(key, name) logger.info("Fingerprint template renamed") @bio.command("delete") @click.pass_context @click.argument("template_id", metavar="ID") @click.option("-P", "--pin", help="PIN code") @click.option("-f", "--force", is_flag=True, help="confirm deletion without prompting") def bio_delete(ctx, template_id, pin, force): """ Delete a fingerprint. Delete a fingerprint from the YubiKey by its ID, which can be seen by running the "list" subcommand. """ bio = _init_bio(ctx, pin) enrollments = bio.enumerate_enrollments() try: key: Optional[bytes] = bytes.fromhex(template_id) except ValueError: key = None if key not in enrollments: # Match using template_id as NAME matches = [k for k in enrollments if enrollments[k] == template_id] if len(matches) == 0: raise CliFail(f"No fingerprint matching ID={template_id}") elif len(matches) > 1: raise CliFail( f"Multiple matches for NAME={template_id}. " "Delete by template ID instead." ) key = matches[0] name = enrollments[key] if force or click.confirm(f"Delete fingerprint {_format_fp(key, name)}?"): try: bio.remove_enrollment(key) logger.info("Fingerprint template deleted") except CtapError as e: raise CliFail(f"Failed to delete fingerprint: {e.code.name}")
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/fido.py
fido.py
from yubikit.core import TRANSPORT from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from yubikit.management import CAPABILITY, USB_INTERFACE from yubikit.yubiotp import YubiOtpSession from yubikit.oath import OathSession from yubikit.support import get_name from .util import CliFail, is_yk4_fips, click_command from ..otp import is_in_fips_mode as otp_in_fips_mode from ..oath import is_in_fips_mode as oath_in_fips_mode from ..fido import is_in_fips_mode as ctap_in_fips_mode from typing import List import click import logging logger = logging.getLogger(__name__) def print_app_status_table(supported_apps, enabled_apps): usb_supported = supported_apps.get(TRANSPORT.USB, 0) usb_enabled = enabled_apps.get(TRANSPORT.USB, 0) nfc_supported = supported_apps.get(TRANSPORT.NFC, 0) nfc_enabled = enabled_apps.get(TRANSPORT.NFC, 0) rows = [] for app in CAPABILITY: if app & usb_supported: if app & usb_enabled: usb_status = "Enabled" else: usb_status = "Disabled" else: usb_status = "Not available" if nfc_supported: if app & nfc_supported: if app & nfc_enabled: nfc_status = "Enabled" else: nfc_status = "Disabled" else: nfc_status = "Not available" rows.append([app.display_name, usb_status, nfc_status]) else: rows.append([app.display_name, usb_status]) column_l: List[int] = [] for row in rows: for idx, c in enumerate(row): if len(column_l) > idx: if len(c) > column_l[idx]: column_l[idx] = len(c) else: column_l.append(len(c)) f_apps = "Applications".ljust(column_l[0]) if nfc_supported: f_USB = "USB".ljust(column_l[1]) f_NFC = "NFC".ljust(column_l[2]) f_table = "" for row in rows: for idx, c in enumerate(row): f_table += f"{c.ljust(column_l[idx])}\t" f_table = f_table.strip() + "\n" if nfc_supported: click.echo(f"{f_apps}\t{f_USB}\t{f_NFC}") else: click.echo(f"{f_apps}") click.echo(f_table, nl=False) def get_overall_fips_status(device, info): statuses = {} usb_enabled = info.config.enabled_capabilities[TRANSPORT.USB] statuses["OTP"] = False if usb_enabled & CAPABILITY.OTP: with device.open_connection(OtpConnection) as conn: otp_app = YubiOtpSession(conn) statuses["OTP"] = otp_in_fips_mode(otp_app) statuses["OATH"] = False if usb_enabled & CAPABILITY.OATH: with device.open_connection(SmartCardConnection) as conn: oath_app = OathSession(conn) statuses["OATH"] = oath_in_fips_mode(oath_app) statuses["FIDO U2F"] = False if usb_enabled & CAPABILITY.U2F: with device.open_connection(FidoConnection) as conn: statuses["FIDO U2F"] = ctap_in_fips_mode(conn) return statuses def _check_fips_status(device, info): fips_status = get_overall_fips_status(device, info) click.echo() click.echo(f"FIPS Approved Mode: {'Yes' if all(fips_status.values()) else 'No'}") status_keys = list(fips_status.keys()) status_keys.sort() for status_key in status_keys: click.echo(f" {status_key}: {'Yes' if fips_status[status_key] else 'No'}") @click.option( "-c", "--check-fips", help="check if YubiKey is in FIPS Approved mode (YubiKey 4 FIPS only)", is_flag=True, ) @click_command(connections=[SmartCardConnection, OtpConnection, FidoConnection]) @click.pass_context def info(ctx, check_fips): """ Show general information. Displays information about the attached YubiKey such as serial number, firmware version, capabilities, etc. """ info = ctx.obj["info"] pid = ctx.obj["pid"] if pid is None: interfaces = None key_type = None else: interfaces = pid.usb_interfaces key_type = pid.yubikey_type device_name = get_name(info, key_type) click.echo(f"Device type: {device_name}") if info.serial: click.echo(f"Serial number: {info.serial}") if info.version: f_version = ".".join(str(x) for x in info.version) click.echo(f"Firmware version: {f_version}") else: click.echo( "Firmware version: Uncertain, re-run with only one YubiKey connected" ) if info.form_factor: click.echo(f"Form factor: {info.form_factor!s}") if interfaces: f_interfaces = ", ".join( t.name or str(t) for t in USB_INTERFACE if t in USB_INTERFACE(interfaces) ) click.echo(f"Enabled USB interfaces: {f_interfaces}") if TRANSPORT.NFC in info.supported_capabilities: f_nfc = ( "enabled" if info.config.enabled_capabilities.get(TRANSPORT.NFC) else "disabled" ) click.echo(f"NFC transport is {f_nfc}.") if info.is_locked: click.echo("Configured capabilities are protected by a lock code.") click.echo() print_app_status_table( info.supported_capabilities, info.config.enabled_capabilities ) if check_fips: if is_yk4_fips(info): device = ctx.obj["device"] _check_fips_status(device, info) else: raise CliFail("Unable to check FIPS Approved mode - Not a YubiKey 4 FIPS")
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/info.py
info.py
from yubikit.core.smartcard import SmartCardConnection from yubikit.hsmauth import ( HsmAuthSession, InvalidPinError, ALGORITHM, MANAGEMENT_KEY_LEN, DEFAULT_MANAGEMENT_KEY, ) from yubikit.core.smartcard import ApduError, SW from ..util import parse_private_key, InvalidPasswordError from ..hsmauth import ( get_hsmauth_info, generate_random_management_key, ) from .util import ( CliFail, click_force_option, click_postpone_execution, click_callback, click_format_option, click_prompt, click_group, pretty_print, ) from cryptography.hazmat.primitives import serialization import click import os import logging logger = logging.getLogger(__name__) def handle_credential_error(e: Exception, default_exception_msg): if isinstance(e, InvalidPinError): attempts = e.attempts_remaining if attempts: raise CliFail(f"Wrong management key, {attempts} attempts remaining.") else: raise CliFail("Management key is blocked.") elif isinstance(e, ApduError): if e.sw == SW.AUTH_METHOD_BLOCKED: raise CliFail("A credential with the provided label already exists.") elif e.sw == SW.NO_SPACE: raise CliFail("No space left on the YubiKey for YubiHSM Auth credentials.") elif e.sw == SW.FILE_NOT_FOUND: raise CliFail("Credential with the provided label was not found.") elif e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: raise CliFail("The device was not touched.") raise CliFail(default_exception_msg) def _parse_touch_required(touch_required: bool) -> str: if touch_required: return "On" else: return "Off" def _parse_algorithm(algorithm: ALGORITHM) -> str: if algorithm == ALGORITHM.AES128_YUBICO_AUTHENTICATION: return "Symmetric" else: return "Asymmetric" def _parse_key(key, key_len, key_type): try: key = bytes.fromhex(key) except Exception: ValueError(key) if len(key) != key_len: raise ValueError( f"{key_type} must be exactly {key_len} bytes long " f"({key_len*2} hexadecimal digits) long" ) return key def _parse_hex(hex): try: val = bytes.fromhex(hex) return val except Exception: raise ValueError(hex) @click_callback() def click_parse_management_key(ctx, param, val): return _parse_key(val, MANAGEMENT_KEY_LEN, "Management key") @click_callback() def click_parse_enc_key(ctx, param, val): return _parse_key(val, ALGORITHM.AES128_YUBICO_AUTHENTICATION.key_len, "ENC key") @click_callback() def click_parse_mac_key(ctx, param, val): return _parse_key(val, ALGORITHM.AES128_YUBICO_AUTHENTICATION.key_len, "MAC key") @click_callback() def click_parse_card_crypto(ctx, param, val): return _parse_hex(val) @click_callback() def click_parse_context(ctx, param, val): return _parse_hex(val) def _prompt_management_key(prompt="Enter a management key [blank to use default key]"): management_key = click_prompt( prompt, default="", hide_input=True, show_default=False ) if management_key == "": return DEFAULT_MANAGEMENT_KEY return _parse_key(management_key, MANAGEMENT_KEY_LEN, "Management key") def _prompt_credential_password(prompt="Enter credential password"): credential_password = click_prompt( prompt, default="", hide_input=True, show_default=False ) return credential_password def _prompt_symmetric_key(type): symmetric_key = click_prompt(f"Enter {type}", default="", show_default=False) return _parse_key( symmetric_key, ALGORITHM.AES128_YUBICO_AUTHENTICATION.key_len, "ENC key" ) def _fname(fobj): return getattr(fobj, "name", fobj) click_credential_password_option = click.option( "-c", "--credential-password", help="password to protect credential" ) click_management_key_option = click.option( "-m", "--management-key", help="the management key", callback=click_parse_management_key, ) click_touch_option = click.option( "-t", "--touch", is_flag=True, help="require touch on YubiKey to access credential" ) @click_group(connections=[SmartCardConnection]) @click.pass_context @click_postpone_execution def hsmauth(ctx): """ Manage the YubiHSM Auth application """ dev = ctx.obj["device"] conn = dev.open_connection(SmartCardConnection) ctx.call_on_close(conn.close) ctx.obj["session"] = HsmAuthSession(conn) @hsmauth.command() @click.pass_context def info(ctx): """ Display general status of the YubiHSM Auth application. """ info = get_hsmauth_info(ctx.obj["session"]) click.echo("\n".join(pretty_print(info))) @hsmauth.command() @click.pass_context @click_force_option def reset(ctx, force): """ Reset all YubiHSM Auth data. This action will wipe all data and restore factory setting for the YubiHSM Auth application on the YubiKey. """ force or click.confirm( "WARNING! This will delete all stored YubiHSM Auth data and restore factory " "setting. Proceed?", abort=True, err=True, ) click.echo("Resetting YubiHSM Auth data...") ctx.obj["session"].reset() click.echo("Success! All YubiHSM Auth data have been cleared from the YubiKey.") click.echo( "Your YubiKey now has the default Management Key" f"({DEFAULT_MANAGEMENT_KEY.hex()})." ) @hsmauth.group() def credentials(): """Manage YubiHSM Auth credentials.""" @credentials.command() @click.pass_context def list(ctx): """ List all credentials. List all credentials stored on the YubiKey. """ session = ctx.obj["session"] creds = session.list_credentials() if len(creds) == 0: click.echo("No items found") else: click.echo(f"Found {len(creds)} item(s)") max_size_label = max(len(cred.label) for cred in creds) max_size_type = ( 10 if any( c.algorithm == ALGORITHM.EC_P256_YUBICO_AUTHENTICATION for c in creds ) else 9 ) format_str = "{0: <{label_width}}\t{1: <{type_width}}\t{2}\t{3}" click.echo( format_str.format( "Label", "Type", "Touch", "Retries", label_width=max_size_label, type_width=max_size_type, ) ) for cred in creds: click.echo( format_str.format( cred.label, _parse_algorithm(cred.algorithm), _parse_touch_required(cred.touch_required), cred.counter, label_width=max_size_label, type_width=max_size_type, ) ) @credentials.command() @click.pass_context @click.argument("label") @click_credential_password_option @click_management_key_option @click_touch_option def generate(ctx, label, credential_password, management_key, touch): """Generate an asymmetric credential. This will generate an asymmetric YubiHSM Auth credential (private key) on the YubiKey. \b LABEL label for the YubiHSM Auth credential """ if not credential_password: credential_password = _prompt_credential_password() if not management_key: management_key = _prompt_management_key() session = ctx.obj["session"] try: session.generate_credential_asymmetric( management_key, label, credential_password, touch ) except Exception as e: handle_credential_error( e, default_exception_msg="Failed to generate asymmetric credential." ) @credentials.command("import") @click.pass_context @click.argument("label") @click.argument("private-key", type=click.File("rb"), metavar="PRIVATE-KEY") @click.option("-p", "--password", help="password used to decrypt the private key") @click_credential_password_option @click_management_key_option @click_touch_option def import_credential( ctx, label, private_key, password, credential_password, management_key, touch ): """Import an asymmetric credential. This will import a private key as an asymmetric YubiHSM Auth credential to the YubiKey. \b LABEL label for the YubiHSM Auth credential PRIVATE-KEY file containing the private key (use '-' to use stdin) """ if not credential_password: credential_password = _prompt_credential_password() if not management_key: management_key = _prompt_management_key() session = ctx.obj["session"] data = private_key.read() while True: if password is not None: password = password.encode() try: private_key = parse_private_key(data, password) except InvalidPasswordError: logger.debug("Error parsing key", exc_info=True) if password is None: password = click_prompt( "Enter password to decrypt key", default="", hide_input=True, show_default=False, ) continue else: password = None click.echo("Wrong password.") continue break try: session.put_credential_asymmetric( management_key, label, private_key, credential_password, touch, ) except Exception as e: handle_credential_error( e, default_exception_msg="Failed to import asymmetric credential." ) @credentials.command() @click.pass_context @click.argument("label") @click.argument("public-key-output", type=click.File("wb"), metavar="PUBLIC-KEY") @click_format_option def export(ctx, label, public_key_output, format): """Export the public key corresponding to an asymmetric credential. This will export the long-term public key corresponding to the asymmetric YubiHSM Auth credential stored on the YubiKey. \b LABEL label for the YubiHSM Auth credential PUBLIC-KEY file to write the public key to (use '-' to use stdout) """ session = ctx.obj["session"] try: public_key = session.get_public_key(label) key_encoding = format public_key_encoded = public_key.public_bytes( encoding=key_encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) public_key_output.write(public_key_encoded) logger.info(f"Public key for {label} written to {_fname(public_key_output)}") except ApduError as e: if e.sw == SW.AUTH_METHOD_BLOCKED: raise CliFail("The entry is not an asymmetric credential.") elif e.sw == SW.FILE_NOT_FOUND: raise CliFail("Credential not found.") else: raise CliFail("Unable to export public key.") @credentials.command() @click.pass_context @click.argument("label") @click.option("-E", "--enc-key", help="the ENC key", callback=click_parse_enc_key) @click.option("-M", "--mac-key", help="the MAC key", callback=click_parse_mac_key) @click.option( "-g", "--generate", is_flag=True, help="generate a random encryption and mac key" ) @click_credential_password_option @click_management_key_option @click_touch_option def symmetric( ctx, label, credential_password, management_key, enc_key, mac_key, generate, touch ): """Import a symmetric credential. This will import an encryption and mac key as a symmetric YubiHSM Auth credential on the YubiKey. \b LABEL label for the YubiHSM Auth credential """ if not credential_password: credential_password = _prompt_credential_password() if not management_key: management_key = _prompt_management_key() if generate and (enc_key or mac_key): ctx.fail("--enc-key and --mac-key cannot be combined with --generate") if generate: enc_key = os.urandom(ALGORITHM.AES128_YUBICO_AUTHENTICATION.key_len) mac_key = os.urandom(ALGORITHM.AES128_YUBICO_AUTHENTICATION.key_len) click.echo("Generated ENC and MAC keys:") click.echo("\n".join(pretty_print({"ENC-KEY": enc_key, "MAC-KEY": mac_key}))) if not enc_key: enc_key = _prompt_symmetric_key("ENC key") if not mac_key: mac_key = _prompt_symmetric_key("MAC key") session = ctx.obj["session"] try: session.put_credential_symmetric( management_key, label, enc_key, mac_key, credential_password, touch, ) except Exception as e: handle_credential_error( e, default_exception_msg="Failed to import symmetric credential." ) @credentials.command() @click.pass_context @click.argument("label") @click.option( "-d", "--derivation-password", help="deriviation password for ENC and MAC keys" ) @click_credential_password_option @click_management_key_option @click_touch_option def derive(ctx, label, derivation_password, credential_password, management_key, touch): """Import a symmetric credential derived from a password. This will import a symmetric YubiHSM Auth credential by deriving ENC and MAC keys from a password. \b LABEL label for the YubiHSM Auth credential """ if not credential_password: credential_password = _prompt_credential_password() if not management_key: management_key = _prompt_management_key() if not derivation_password: derivation_password = click_prompt( "Enter derivation password", default="", show_default=False ) session = ctx.obj["session"] try: session.put_credential_derived( management_key, label, credential_password, derivation_password, touch ) except Exception as e: handle_credential_error( e, default_exception_msg="Failed to import symmetric credential." ) @credentials.command() @click.pass_context @click.argument("label") @click_management_key_option @click_force_option def delete(ctx, label, management_key, force): """ Delete a credential. This will delete a YubiHSM Auth credential from the YubiKey. \b LABEL a label to match a single credential (as shown in "list") """ if not management_key: management_key = _prompt_management_key() force or click.confirm( f"Delete credential: {label} ?", abort=True, err=True, ) session = ctx.obj["session"] try: session.delete_credential(management_key, label) except Exception as e: handle_credential_error( e, default_exception_msg="Failed to delete credential.", ) @hsmauth.group() def access(): """Manage Management Key for YubiHSM Auth""" @access.command() @click.pass_context @click.option( "-m", "--management-key", help="current management key", default=DEFAULT_MANAGEMENT_KEY, show_default=True, callback=click_parse_management_key, ) @click.option( "-n", "--new-management-key", help="a new management key to set", callback=click_parse_management_key, ) @click.option( "-g", "--generate", is_flag=True, help="generate a random management key " "(can't be used with --new-management-key)", ) def change_management_key(ctx, management_key, new_management_key, generate): """ Change the management key. Allows you to change the management key which is required to add and delete YubiHSM Auth credentials stored on the YubiKey. """ if not management_key: management_key = _prompt_management_key( "Enter current management key [blank to use default key]" ) session = ctx.obj["session"] # Can't combine new key with generate. if new_management_key and generate: ctx.fail("Invalid options: --new-management-key conflicts with --generate") if not new_management_key: if generate: new_management_key = generate_random_management_key() click.echo(f"Generated management key: {new_management_key.hex()}") else: try: new_management_key = bytes.fromhex( click_prompt( "Enter the new management key", hide_input=True, confirmation_prompt=True, ) ) except Exception: ctx.fail("New management key has the wrong format.") if len(new_management_key) != MANAGEMENT_KEY_LEN: raise CliFail( "Management key has the wrong length (expected %d bytes)" % MANAGEMENT_KEY_LEN ) try: session.put_management_key(management_key, new_management_key) except Exception as e: handle_credential_error( e, default_exception_msg="Failed to change management key." )
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/hsmauth.py
hsmauth.py
from yubikit.core import TRANSPORT, YUBIKEY from yubikit.core.otp import OtpConnection from yubikit.core.smartcard import SmartCardConnection from yubikit.core.fido import FidoConnection from yubikit.management import ( ManagementSession, DeviceConfig, CAPABILITY, USB_INTERFACE, DEVICE_FLAG, Mode, ) from .util import ( click_group, click_postpone_execution, click_force_option, click_prompt, EnumChoice, CliFail, ) import os import re import click import logging logger = logging.getLogger(__name__) CLEAR_LOCK_CODE = b"\0" * 16 def prompt_lock_code(): return click_prompt("Enter your lock code", hide_input=True) @click_group(connections=[SmartCardConnection, OtpConnection, FidoConnection]) @click.pass_context @click_postpone_execution def config(ctx): """ Enable or disable applications. The applications may be enabled and disabled independently over different transports (USB and NFC). The configuration may also be protected by a lock code. Examples: \b Disable PIV over NFC: $ ykman config nfc --disable PIV \b Enable all applications over USB: $ ykman config usb --enable-all \b Generate and set a random application lock code: $ ykman config set-lock-code --generate """ dev = ctx.obj["device"] for conn_type in (SmartCardConnection, OtpConnection, FidoConnection): if dev.supports_connection(conn_type): try: conn = dev.open_connection(conn_type) ctx.call_on_close(conn.close) ctx.obj["controller"] = ManagementSession(conn) return except Exception: logger.warning( f"Failed connecting to the YubiKey over {conn_type}", exc_info=True ) raise CliFail("Couldn't connect to the YubiKey.") def _require_config(ctx): info = ctx.obj["info"] if (1, 0, 0) < info.version < (5, 0, 0): raise CliFail( "Configuring applications is not supported on this YubiKey. " "Use the `mode` command to configure USB interfaces." ) @config.command("set-lock-code") @click.pass_context @click_force_option @click.option("-l", "--lock-code", metavar="HEX", help="current lock code") @click.option( "-n", "--new-lock-code", metavar="HEX", help="new lock code (can't be used with --generate)", ) @click.option("-c", "--clear", is_flag=True, help="clear the lock code") @click.option( "-g", "--generate", is_flag=True, help="generate a random lock code (can't be used with --new-lock-code)", ) def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force): """ Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value. """ _require_config(ctx) info = ctx.obj["info"] app = ctx.obj["controller"] if sum(1 for arg in [new_lock_code, generate, clear] if arg) > 1: raise CliFail( "Invalid options: Only one of --new-lock-code, --generate, " "and --clear may be used." ) # Get the new lock code to set if clear: set_code = CLEAR_LOCK_CODE elif generate: set_code = os.urandom(16) click.echo(f"Using a randomly generated lock code: {set_code.hex()}") force or click.confirm( "Lock configuration with this lock code?", abort=True, err=True ) else: if not new_lock_code: new_lock_code = click_prompt( "Enter your new lock code", hide_input=True, confirmation_prompt=True ) set_code = _parse_lock_code(ctx, new_lock_code) # Get the current lock code to use if info.is_locked: if not lock_code: lock_code = click_prompt("Enter your current lock code", hide_input=True) use_code = _parse_lock_code(ctx, lock_code) else: if lock_code: raise CliFail( "No lock code is currently set. Use --new-lock-code to set one." ) use_code = None # Set new lock code try: app.write_device_config( None, False, use_code, set_code, ) logger.info("Lock code updated") except Exception: if info.is_locked: raise CliFail("Failed to change the lock code. Wrong current code?") raise CliFail("Failed to set the lock code.") def _configure_applications( ctx, config, changes, transport, enable, disable, lock_code, force, ): _require_config(ctx) info = ctx.obj["info"] supported = info.supported_capabilities.get(transport) enabled = info.config.enabled_capabilities.get(transport) if not supported: raise CliFail(f"{transport} not supported on this YubiKey.") if enable & disable: ctx.fail("Invalid options.") unsupported = ~supported & (enable | disable) if unsupported: raise CliFail( f"{unsupported.display_name} not supported over {transport} on this " "YubiKey." ) new_enabled = (enabled | enable) & ~disable if transport == TRANSPORT.USB: if sum(CAPABILITY) & new_enabled == 0: ctx.fail(f"Can not disable all applications over {transport}.") reboot = enabled.usb_interfaces != new_enabled.usb_interfaces else: reboot = False if enable: changes.append(f"Enable {enable.display_name}") if disable: changes.append(f"Disable {disable.display_name}") if reboot: changes.append("The YubiKey will reboot") is_locked = info.is_locked if force and is_locked and not lock_code: raise CliFail("Configuration is locked - please supply the --lock-code option.") if lock_code and not is_locked: raise CliFail( "Configuration is not locked - please remove the --lock-code option." ) click.echo(f"{transport} configuration changes:") for change in changes: click.echo(f" {change}") force or click.confirm("Proceed?", abort=True, err=True) if is_locked and not lock_code: lock_code = prompt_lock_code() if lock_code: lock_code = _parse_lock_code(ctx, lock_code) config.enabled_capabilities = {transport: new_enabled} app = ctx.obj["controller"] try: app.write_device_config( config, reboot, lock_code, ) logger.info(f"{transport} application configuration updated") except Exception: raise CliFail(f"Failed to configure {transport} applications.") @config.command() @click.pass_context @click_force_option @click.option( "-e", "--enable", multiple=True, type=EnumChoice(CAPABILITY), help="enable applications", ) @click.option( "-d", "--disable", multiple=True, type=EnumChoice(CAPABILITY), help="disable applications", ) @click.option( "-l", "--list", "list_enabled", is_flag=True, help="list enabled applications" ) @click.option("-a", "--enable-all", is_flag=True, help="enable all applications") @click.option( "-L", "--lock-code", metavar="HEX", help="current application configuration lock code", ) @click.option( "--touch-eject", is_flag=True, help="when set, the button toggles the state" " of the smartcard between ejected and inserted (CCID only)", ) @click.option("--no-touch-eject", is_flag=True, help="disable touch eject (CCID only)") @click.option( "--autoeject-timeout", required=False, type=int, default=None, metavar="SECONDS", help="when set, the smartcard will automatically eject" " after the given time (implies --touch-eject)", ) @click.option( "--chalresp-timeout", required=False, type=int, default=None, metavar="SECONDS", help="sets the timeout when waiting for touch for challenge-response in the OTP " "application", ) def usb( ctx, enable, disable, list_enabled, enable_all, touch_eject, no_touch_eject, autoeject_timeout, chalresp_timeout, lock_code, force, ): """ Enable or disable applications over USB. """ _require_config(ctx) if not ( list_enabled or enable_all or enable or disable or touch_eject or no_touch_eject or autoeject_timeout or chalresp_timeout ): ctx.fail("No configuration options chosen.") if touch_eject and no_touch_eject: ctx.fail("Invalid options.") if list_enabled: _list_apps(ctx, TRANSPORT.USB) config = DeviceConfig({}, autoeject_timeout, chalresp_timeout, None) changes = [] info = ctx.obj["info"] if enable_all: enable = info.supported_capabilities.get(TRANSPORT.USB) else: enable = CAPABILITY(sum(enable)) disable = CAPABILITY(sum(disable)) if touch_eject: config.device_flags = info.config.device_flags | DEVICE_FLAG.EJECT changes.append("Enable touch-eject") if no_touch_eject: config.device_flags = info.config.device_flags & ~DEVICE_FLAG.EJECT changes.append("Disable touch-eject") if autoeject_timeout: changes.append(f"Set auto-eject timeout to {autoeject_timeout}") if chalresp_timeout: changes.append(f"Set challenge-response timeout to {chalresp_timeout}") _configure_applications( ctx, config, changes, TRANSPORT.USB, enable, disable, lock_code, force, ) @config.command() @click.pass_context @click_force_option @click.option( "-e", "--enable", multiple=True, type=EnumChoice(CAPABILITY), help="enable applications", ) @click.option( "-d", "--disable", multiple=True, type=EnumChoice(CAPABILITY), help="disable applications", ) @click.option("-a", "--enable-all", is_flag=True, help="enable all applications") @click.option("-D", "--disable-all", is_flag=True, help="disable all applications") @click.option( "-l", "--list", "list_enabled", is_flag=True, help="list enabled applications" ) @click.option( "-L", "--lock-code", metavar="HEX", help="current application configuration lock code", ) def nfc(ctx, enable, disable, enable_all, disable_all, list_enabled, lock_code, force): """ Enable or disable applications over NFC. """ _require_config(ctx) if not (list_enabled or enable_all or enable or disable_all or disable): ctx.fail("No configuration options chosen.") if list_enabled: _list_apps(ctx, TRANSPORT.NFC) config = DeviceConfig({}, None, None, None) info = ctx.obj["info"] nfc_supported = info.supported_capabilities.get(TRANSPORT.NFC) if enable_all: enable = nfc_supported else: enable = CAPABILITY(sum(enable)) if disable_all: disable = nfc_supported else: disable = CAPABILITY(sum(disable)) _configure_applications( ctx, config, [], TRANSPORT.NFC, enable, disable, lock_code, force, ) def _list_apps(ctx, transport): enabled = ctx.obj["info"].config.enabled_capabilities.get(transport) if enabled is None: raise CliFail(f"{transport} not supported on this YubiKey.") for app in CAPABILITY: if app & enabled: click.echo(app.display_name) ctx.exit() def _ensure_not_invalid_options(ctx, enable, disable): if enable & disable: ctx.fail("Invalid options.") def _parse_lock_code(ctx, lock_code): try: lock_code = bytes.fromhex(lock_code) if lock_code and len(lock_code) != 16: ctx.fail("Lock code must be exactly 16 bytes (32 hexadecimal digits) long.") return lock_code except Exception: ctx.fail("Lock code has the wrong format.") # MODE def _parse_interface_string(interface): for iface in USB_INTERFACE: if (iface.name or "").startswith(interface): return iface raise ValueError() def _parse_mode_string(ctx, param, mode): try: mode_int = int(mode) return Mode.from_code(mode_int) except IndexError: ctx.fail(f"Invalid mode: {mode_int}") except ValueError: pass # Not a numeric mode, parse string try: if mode[0] in ["+", "-"]: info = ctx.obj["info"] usb_enabled = info.config.enabled_capabilities[TRANSPORT.USB] interfaces = usb_enabled.usb_interfaces for mod in re.findall(r"[+-][A-Z]+", mode.upper()): interface = _parse_interface_string(mod[1:]) if mod.startswith("+"): interfaces |= interface else: interfaces ^= interface else: interfaces = USB_INTERFACE(0) for t in re.split(r"[+]+", mode.upper()): if t: interfaces |= _parse_interface_string(t) except ValueError: ctx.fail(f"Invalid mode string: {mode}") return Mode(interfaces) @config.command() @click.argument("mode", callback=_parse_mode_string) @click.option( "--touch-eject", is_flag=True, help="when set, the button " "toggles the state of the smartcard between ejected and inserted " "(CCID only)", ) @click.option( "--autoeject-timeout", required=False, type=int, default=0, metavar="SECONDS", help="when set, the smartcard will automatically eject after the given time " "(implies --touch-eject, CCID only)", ) @click.option( "--chalresp-timeout", required=False, type=int, default=0, metavar="SECONDS", help="sets the timeout when waiting for touch for challenge response", ) @click_force_option @click.pass_context def mode(ctx, mode, touch_eject, autoeject_timeout, chalresp_timeout, force): """ Manage connection modes (USB Interfaces). This command is generaly used with YubiKeys prior to the 5 series. Use "ykman config usb" for more granular control on YubiKey 5 and later. Get the current connection mode of the YubiKey, or set it to MODE. MODE can be a string, such as "OTP+FIDO+CCID", or a shortened form: "o+f+c". It can also be a mode number. Examples: \b Set the OTP and FIDO mode: $ ykman config mode OTP+FIDO \b Set the CCID only mode and use touch to eject the smart card: $ ykman config mode CCID --touch-eject """ info = ctx.obj["info"] mgmt = ctx.obj["controller"] usb_enabled = info.config.enabled_capabilities[TRANSPORT.USB] my_mode = Mode(usb_enabled.usb_interfaces) usb_supported = info.supported_capabilities[TRANSPORT.USB] interfaces_supported = usb_supported.usb_interfaces pid = ctx.obj["pid"] if pid: key_type = pid.yubikey_type else: key_type = None if autoeject_timeout: # autoeject implies touch eject touch_eject = True autoeject = autoeject_timeout if touch_eject else None if mode.interfaces != USB_INTERFACE.CCID: if touch_eject: ctx.fail("--touch-eject can only be used when setting CCID-only mode") if not force: if mode == my_mode: raise CliFail(f"Mode is already {mode}, nothing to do...", 0) elif key_type in (YUBIKEY.YKS, YUBIKEY.YKP): raise CliFail( "Mode switching is not supported on this YubiKey!\n" "Use --force to attempt to set it anyway." ) elif mode.interfaces not in interfaces_supported: raise CliFail( f"Mode {mode} is not supported on this YubiKey!\n" + "Use --force to attempt to set it anyway." ) force or click.confirm(f"Set mode of YubiKey to {mode}?", abort=True, err=True) try: mgmt.set_mode(mode, chalresp_timeout, autoeject) logger.info("USB mode updated") click.echo( "Mode set! You must remove and re-insert your YubiKey " "for this change to take effect." ) except Exception: raise CliFail( "Failed to switch mode on the YubiKey. Make sure your " "YubiKey does not have an access code set." )
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/config.py
config.py
from base64 import b32encode from yubikit.yubiotp import ( SLOT, NDEF_TYPE, YubiOtpSession, YubiOtpSlotConfiguration, HmacSha1SlotConfiguration, StaticPasswordSlotConfiguration, HotpSlotConfiguration, UpdateConfiguration, ) from yubikit.core import TRANSPORT, CommandError from yubikit.core.otp import ( MODHEX_ALPHABET, modhex_encode, modhex_decode, OtpConnection, ) from yubikit.core.smartcard import SmartCardConnection from .util import ( CliFail, click_group, click_force_option, click_callback, click_parse_b32_key, click_postpone_execution, click_prompt, prompt_for_touch, EnumChoice, is_yk4_fips, ) from .. import __version__ from ..scancodes import encode, KEYBOARD_LAYOUT from ..otp import ( _PrepareUploadFailed, _prepare_upload_key, is_in_fips_mode, generate_static_pw, parse_oath_key, parse_b32_key, time_challenge, format_oath_code, format_csv, ) from threading import Event from time import time import logging import os import struct import click import webbrowser logger = logging.getLogger(__name__) def parse_hex(length): @click_callback() def inner(ctx, param, val): val = bytes.fromhex(val) if len(val) != length: raise ValueError(f"Must be exactly {length} bytes.") return val return inner def parse_access_code_hex(access_code_hex): try: access_code = bytes.fromhex(access_code_hex) except TypeError as e: raise ValueError(e) if len(access_code) != 6: raise ValueError("Must be exactly 6 bytes.") return access_code click_slot_argument = click.argument( "slot", type=click.Choice(["1", "2"]), callback=lambda c, p, v: SLOT(int(v)) ) _WRITE_FAIL_MSG = ( "Failed to write to the YubiKey. Make sure the device does not " 'have restricted access (see "ykman otp --help" for more info).' ) def _confirm_slot_overwrite(slot_state, slot): if slot_state.is_configured(slot): click.confirm( f"Slot {slot} is already configured. Overwrite configuration?", abort=True, err=True, ) def _fname(fobj): return getattr(fobj, "name", fobj) @click_group(connections=[OtpConnection, SmartCardConnection]) @click.pass_context @click_postpone_execution @click.option( "--access-code", required=False, metavar="HEX", help='6 byte access code (use "-" as a value to prompt for input)', ) def otp(ctx, access_code): """ Manage the YubiOTP application. The YubiKey provides two keyboard-based slots which can each be configured with a credential. Several credential types are supported. A slot configuration may be write-protected with an access code. This prevents the configuration to be overwritten without the access code provided. Mode switching the YubiKey is not possible when a slot is configured with an access code. To provide an access code to commands which require it, use the --access-code option. Note that this option must be given directly after the "otp" command, before any sub-command. Examples: \b Swap the configurations between the two slots: $ ykman otp swap \b Program a random challenge-response credential to slot 2: $ ykman otp chalresp --generate 2 \b Program a Yubico OTP credential to slot 1, using the serial as public id: $ ykman otp yubiotp 1 --serial-public-id \b Program a random 38 characters long static password to slot 2: $ ykman otp static --generate 2 --length 38 \b Remove a currently set access code from slot 2): $ ykman otp --access-code 0123456789ab settings 2 --delete-access-code """ """ # TODO: Require OTP for chalresp, or FW < 5.?. Require CCID for HashOTP dev = ctx.obj["device"] if dev.supports_connection(OtpConnection): conn = dev.open_connection(OtpConnection) else: conn = dev.open_connection(SmartCardConnection) ctx.call_on_close(conn.close) ctx.obj["session"] = YubiOtpSession(conn) """ if access_code is not None: if access_code == "-": access_code = click_prompt("Enter the access code", hide_input=True) try: access_code = parse_access_code_hex(access_code) except Exception as e: ctx.fail(f"Failed to parse access code: {e}") ctx.obj["access_code"] = access_code def _get_session(ctx, types=[OtpConnection, SmartCardConnection]): dev = ctx.obj["device"] for conn_type in types: if dev.supports_connection(conn_type): conn = dev.open_connection(conn_type) ctx.call_on_close(conn.close) return YubiOtpSession(conn) raise CliFail( "The connection type required for this command is not supported/enabled on the " "YubiKey" ) @otp.command() @click.pass_context def info(ctx): """ Display general status of the YubiKey OTP slots. """ session = _get_session(ctx) state = session.get_config_state() slot1 = state.is_configured(1) slot2 = state.is_configured(2) click.echo(f"Slot 1: {slot1 and 'programmed' or 'empty'}") click.echo(f"Slot 2: {slot2 and 'programmed' or 'empty'}") if is_yk4_fips(ctx.obj["info"]): click.echo(f"FIPS Approved Mode: {'Yes' if is_in_fips_mode(session) else 'No'}") @otp.command() @click_force_option @click.pass_context def swap(ctx, force): """ Swaps the two slot configurations. """ session = _get_session(ctx) force or click.confirm( "Swap the two slots of the YubiKey?", abort=True, err=True, ) click.echo("Swapping slots...") try: session.swap_slots() except CommandError: raise CliFail(_WRITE_FAIL_MSG) @otp.command() @click_slot_argument @click.pass_context @click.option("-p", "--prefix", help="added before the NDEF payload, typically a URI") @click.option( "-t", "--ndef-type", type=EnumChoice(NDEF_TYPE), default="URI", show_default=True, help="NDEF payload type", ) def ndef(ctx, slot, prefix, ndef_type): """ Configure a slot to be used over NDEF (NFC). \b If "--prefix" is not specified, a default value will be used, based on the type: - For URI the default value is: "https://my.yubico.com/yk/#" - For TEXT the default is an empty string """ info = ctx.obj["info"] session = _get_session(ctx) state = session.get_config_state() if not info.has_transport(TRANSPORT.NFC): raise CliFail("This YubiKey does not support NFC.") if not state.is_configured(slot): raise CliFail(f"Slot {slot} is empty.") try: session.set_ndef_configuration(slot, prefix, ctx.obj["access_code"], ndef_type) except CommandError: raise CliFail(_WRITE_FAIL_MSG) @otp.command() @click_slot_argument @click_force_option @click.pass_context def delete(ctx, slot, force): """ Deletes the configuration stored in a slot. """ session = _get_session(ctx) state = session.get_config_state() if not force and not state.is_configured(slot): raise CliFail("Not possible to delete an empty slot.") force or click.confirm( f"Do you really want to delete the configuration of slot {slot}?", abort=True, err=True, ) click.echo(f"Deleting the configuration in slot {slot}...") try: session.delete_slot(slot, ctx.obj["access_code"]) except CommandError: raise CliFail(_WRITE_FAIL_MSG) @otp.command() @click_slot_argument @click.option( "-P", "--public-id", required=False, help="public identifier prefix", metavar="MODHEX", ) @click.option( "-p", "--private-id", required=False, metavar="HEX", callback=parse_hex(6), help="6 byte private identifier", ) @click.option( "-k", "--key", required=False, metavar="HEX", callback=parse_hex(16), help="16 byte secret key", ) @click.option( "--no-enter", is_flag=True, help="don't send an Enter keystroke after emitting the OTP", ) @click.option( "-S", "--serial-public-id", is_flag=True, required=False, help="use YubiKey serial number as public ID (can't be used with --public-id)", ) @click.option( "-g", "--generate-private-id", is_flag=True, required=False, help="generate a random private ID (can't be used with --private-id)", ) @click.option( "-G", "--generate-key", is_flag=True, required=False, help="generate a random secret key (can't be used with --key)", ) @click.option( "-u", "--upload", is_flag=True, required=False, help="upload credential to YubiCloud (opens a browser, can't be used with --force)", ) @click.option( "-O", "--config-output", type=click.File("a"), required=False, help="file to output the configuration to (existing file will be appended to)", ) @click_force_option @click.pass_context def yubiotp( ctx, slot, public_id, private_id, key, no_enter, force, serial_public_id, generate_private_id, generate_key, upload, config_output, ): """ Program a Yubico OTP credential. """ info = ctx.obj["info"] session = _get_session(ctx) serial = None if public_id and serial_public_id: ctx.fail("Invalid options: --public-id conflicts with --serial-public-id.") if private_id and generate_private_id: ctx.fail("Invalid options: --private-id conflicts with --generate-public-id.") if upload and force: ctx.fail("Invalid options: --upload conflicts with --force.") if key and generate_key: ctx.fail("Invalid options: --key conflicts with --generate-key.") if not public_id: if serial_public_id: try: serial = session.get_serial() except CommandError: raise CliFail("Serial number not set, public ID must be provided") public_id = modhex_encode(b"\xff\x00" + struct.pack(b">I", serial)) click.echo(f"Using YubiKey serial as public ID: {public_id}") elif force: ctx.fail( "Public ID not given. Please remove the --force flag, or " "add the --serial-public-id flag or --public-id option." ) else: public_id = click_prompt("Enter public ID") if len(public_id) % 2: ctx.fail("Invalid public ID, length must be a multiple of 2.") try: public_id = modhex_decode(public_id) except ValueError: ctx.fail(f"Invalid public ID, must be modhex ({MODHEX_ALPHABET}).") if not private_id: if generate_private_id: private_id = os.urandom(6) click.echo(f"Using a randomly generated private ID: {private_id.hex()}") elif force: ctx.fail( "Private ID not given. Please remove the --force flag, or " "add the --generate-private-id flag or --private-id option." ) else: private_id = click_prompt("Enter private ID") private_id = bytes.fromhex(private_id) if not key: if generate_key: key = os.urandom(16) click.echo(f"Using a randomly generated secret key: {key.hex()}") elif force: ctx.fail( "Secret key not given. Please remove the --force flag, or " "add the --generate-key flag or --key option." ) else: key = click_prompt("Enter secret key") key = bytes.fromhex(key) if upload: click.confirm("Upload credential to YubiCloud?", abort=True, err=True) try: upload_url = _prepare_upload_key( key, public_id, private_id, serial=info.serial, user_agent="ykman/" + __version__, ) click.echo("Upload to YubiCloud initiated successfully.") logger.info("Initiated YubiCloud upload") except _PrepareUploadFailed as e: error_msg = "\n".join(e.messages()) raise CliFail("Upload to YubiCloud failed.\n" + error_msg) force or click.confirm( f"Program a YubiOTP credential in slot {slot}?", abort=True, err=True ) access_code = ctx.obj["access_code"] try: session.put_configuration( slot, YubiOtpSlotConfiguration(public_id, private_id, key).append_cr( not no_enter ), access_code, access_code, ) except CommandError: raise CliFail(_WRITE_FAIL_MSG) if config_output: serial = serial or session.get_serial() csv = format_csv(serial, public_id, private_id, key, access_code) config_output.write(csv + "\n") logger.info(f"Configuration parameters written to {_fname(config_output)}") if upload: logger.info("Launching browser for YubiCloud upload") click.echo("Opening upload form in browser: " + upload_url) webbrowser.open_new_tab(upload_url) @otp.command() @click_slot_argument @click.argument("password", required=False) @click.option("-g", "--generate", is_flag=True, help="generate a random password") @click.option( "-l", "--length", metavar="LENGTH", type=click.IntRange(1, 38), default=38, show_default=True, help="length of generated password", ) @click.option( "-k", "--keyboard-layout", type=EnumChoice(KEYBOARD_LAYOUT), default="MODHEX", show_default=True, help="keyboard layout to use for the static password", ) @click.option( "--no-enter", is_flag=True, help="don't send an Enter keystroke after outputting the password", ) @click_force_option @click.pass_context def static(ctx, slot, password, generate, length, keyboard_layout, no_enter, force): """ Configure a static password. To avoid problems with different keyboard layouts, the following characters (upper and lower case) are allowed by default: cbdefghijklnrtuv Use the --keyboard-layout option to allow more characters based on preferred keyboard layout. """ session = _get_session(ctx) if password and len(password) > 38: ctx.fail("Password too long (maximum length is 38 characters).") if generate and not length: ctx.fail("Provide a length for the generated password.") if not password and not generate: password = click_prompt("Enter a static password") elif not password and generate: password = generate_static_pw(length, keyboard_layout) scan_codes = encode(password, keyboard_layout) if not force: _confirm_slot_overwrite(session.get_config_state(), slot) try: session.put_configuration( slot, StaticPasswordSlotConfiguration(scan_codes).append_cr(not no_enter), ctx.obj["access_code"], ctx.obj["access_code"], ) except CommandError: raise CliFail(_WRITE_FAIL_MSG) @otp.command() @click_slot_argument @click.argument("key", required=False) @click.option( "-t", "--touch", is_flag=True, help="require touch on the YubiKey to generate a response", ) @click.option( "-T", "--totp", is_flag=True, required=False, help="use a base32 encoded key (optionally padded) for TOTP credentials", ) @click.option( "-g", "--generate", is_flag=True, required=False, help="generate a random secret key (can't be used with KEY argument)", ) @click_force_option @click.pass_context def chalresp(ctx, slot, key, totp, touch, force, generate): """ Program a challenge-response credential. If KEY is not given, an interactive prompt will ask for it. \b KEY a key given in hex (or base32, if --totp is specified) """ session = _get_session(ctx) if key: if generate: ctx.fail("Invalid options: --generate conflicts with KEY argument.") elif totp: key = parse_b32_key(key) else: key = parse_oath_key(key) else: if force and not generate: ctx.fail( "No secret key given. Please remove the --force flag, " "set the KEY argument or set the --generate flag." ) elif generate: key = os.urandom(20) if totp: b32key = b32encode(key).decode() click.echo(f"Using a randomly generated key (base32): {b32key}") else: click.echo(f"Using a randomly generated key (hex): {key.hex()}") elif totp: while True: key = click_prompt("Enter a secret key (base32)") try: key = parse_b32_key(key) break except Exception as e: click.echo(e) else: key = click_prompt("Enter a secret key") key = parse_oath_key(key) cred_type = "TOTP" if totp else "challenge-response" force or click.confirm( f"Program a {cred_type} credential in slot {slot}?", abort=True, err=True, ) try: session.put_configuration( slot, HmacSha1SlotConfiguration(key).require_touch(touch), ctx.obj["access_code"], ctx.obj["access_code"], ) except CommandError: raise CliFail(_WRITE_FAIL_MSG) @otp.command() @click_slot_argument @click.argument("challenge", required=False) @click.option( "-T", "--totp", is_flag=True, help="generate a TOTP code, use the current time if challenge is omitted", ) @click.option( "-d", "--digits", type=click.Choice(["6", "8"]), default="6", help="number of digits in generated TOTP code (default: 6), " "ignored unless --totp is set", ) @click.pass_context def calculate(ctx, slot, challenge, totp, digits): """ Perform a challenge-response operation. Send a challenge (in hex) to a YubiKey slot with a challenge-response credential, and read the response. Supports output as a OATH-TOTP code. """ dev = ctx.obj["device"] if dev.transport == TRANSPORT.NFC: session = _get_session(ctx, [SmartCardConnection]) else: # Calculate over USB is only available over OtpConnection session = _get_session(ctx, [OtpConnection]) if not challenge and not totp: challenge = click_prompt("Enter a challenge (hex)") # Check that slot is not empty if not session.get_config_state().is_configured(slot): raise CliFail("Cannot perform challenge-response on an empty slot.") if totp: # Challenge omitted or timestamp if challenge is None: challenge = time_challenge(int(time())) else: try: challenge = time_challenge(int(challenge)) except Exception: logger.exception("Error parsing challenge") ctx.fail("Timestamp challenge for TOTP must be an integer.") else: # Challenge is hex challenge = bytes.fromhex(challenge) try: event = Event() def on_keepalive(status): if not hasattr(on_keepalive, "prompted") and status == 2: prompt_for_touch() setattr(on_keepalive, "prompted", True) response = session.calculate_hmac_sha1(slot, challenge, event, on_keepalive) if totp: value = format_oath_code(response, int(digits)) else: value = response.hex() click.echo(value) except CommandError: raise CliFail(_WRITE_FAIL_MSG) def parse_modhex_or_bcd(value): try: return True, modhex_decode(value) except ValueError: try: int(value) return False, bytes.fromhex(value) except ValueError: raise ValueError("value must be modhex or decimal") @otp.command() @click_slot_argument @click.argument("key", callback=click_parse_b32_key, required=False) @click.option( "-d", "--digits", type=click.Choice(["6", "8"]), default="6", help="number of digits in generated code (default is 6)", ) @click.option("-c", "--counter", type=int, default=0, help="initial counter value") @click.option("-i", "--identifier", help="token identifier") @click.option( "--no-enter", is_flag=True, help="don't send an Enter keystroke after outputting the code", ) @click_force_option @click.pass_context def hotp(ctx, slot, key, digits, counter, identifier, no_enter, force): """ Program an HMAC-SHA1 OATH-HOTP credential. The YubiKey can be configured to output an OATH Token Identifier as a prefix to the OTP itself, which consists of OMP+TT+MUI. Using the "--identifier" option, you may specify the OMP+TT as 4 characters, the MUI as 8 characters, or the full OMP+TT+MUI as 12 characters. If omitted, a default value of "ubhe" will be used for OMP+TT, and the YubiKey serial number will be used as MUI. """ session = _get_session(ctx) mh1 = False mh2 = False if identifier: if identifier == "-": identifier = "ubhe" if len(identifier) == 4: identifier += f"{session.get_serial():08}" elif len(identifier) == 8: identifier = "ubhe" + identifier if len(identifier) != 12: raise ValueError("Incorrect length for token identifier.") omp_m, omp = parse_modhex_or_bcd(identifier[:2]) tt_m, tt = parse_modhex_or_bcd(identifier[2:4]) mui_m, mui = parse_modhex_or_bcd(identifier[4:]) if tt_m and not omp_m: raise ValueError("TT can only be modhex encoded if OMP is as well.") if mui_m and not (omp_m and tt_m): raise ValueError( "MUI can only be modhex encoded if OMP and TT are as well." ) token_id = omp + tt + mui if mui_m: mh1 = mh2 = True elif tt_m: mh2 = True elif omp_m: mh1 = True else: token_id = b"" if not key: while True: key = click_prompt("Enter a secret key (base32)") try: key = parse_b32_key(key) break except Exception as e: click.echo(e) force or click.confirm( f"Program a HOTP credential in slot {slot}?", abort=True, err=True ) try: session.put_configuration( slot, HotpSlotConfiguration(key) .imf(counter) .token_id(token_id, mh1, mh2) .digits8(int(digits) == 8) .append_cr(not no_enter), ctx.obj["access_code"], ctx.obj["access_code"], ) except CommandError: raise CliFail(_WRITE_FAIL_MSG) @otp.command() @click_slot_argument @click_force_option @click.pass_context @click.option( "-A", "--new-access-code", metavar="HEX", required=False, help='a new 6 byte access code to set (use "-" as a value to prompt for input)', ) @click.option( "--delete-access-code", is_flag=True, help="remove access code from the slot" ) @click.option( "--enter/--no-enter", default=True, show_default=True, help="send an Enter keystroke after slot output", ) @click.option( "-p", "--pacing", type=click.Choice(["0", "20", "40", "60"]), default="0", show_default=True, help="throttle output speed by adding a delay (in ms) between characters emitted", ) @click.option( "--use-numeric-keypad", is_flag=True, show_default=True, help="use scancodes for numeric keypad when sending digits " "(helps for some keyboard layouts)", ) def settings( ctx, slot, new_access_code, delete_access_code, enter, pacing, use_numeric_keypad, force, ): """ Update the settings for a slot. Change the settings for a slot without changing the stored secret. All settings not specified will be written with default values. """ session = _get_session(ctx) if new_access_code and delete_access_code: ctx.fail("--new-access-code conflicts with --delete-access-code.") if delete_access_code and not ctx.obj["access_code"]: raise CliFail( "--delete-access-code used without providing an access code " '(see "ykman otp --help" for more info).' ) if not session.get_config_state().is_configured(slot): raise CliFail("Not possible to update settings on an empty slot.") if new_access_code is None: if not delete_access_code: new_access_code = ctx.obj["access_code"] else: if new_access_code == "-": new_access_code = click_prompt( "Enter new access code", hide_input=True, confirmation_prompt=True ) try: new_access_code = parse_access_code_hex(new_access_code) except Exception as e: ctx.fail("Failed to parse access code: " + str(e)) force or click.confirm( f"Update the settings for slot {slot}? " "All existing settings will be overwritten.", abort=True, err=True, ) click.echo(f"Updating settings for slot {slot}...") pacing_bits = int(pacing or "0") // 20 pacing_10ms = bool(pacing_bits & 1) pacing_20ms = bool(pacing_bits & 2) try: session.update_configuration( slot, UpdateConfiguration() .append_cr(enter) .use_numeric(use_numeric_keypad) .pacing(pacing_10ms, pacing_20ms), new_access_code, ctx.obj["access_code"], ) except CommandError: raise CliFail(_WRITE_FAIL_MSG)
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/otp.py
otp.py
from binascii import a2b_hex from yubikit.core.smartcard import ( SmartCardConnection, SmartCardProtocol, ApduError, SW, AID, ) from .util import EnumChoice, CliFail, click_command from typing import Tuple, Optional import re import sys import click import struct import logging logger = logging.getLogger(__name__) APDU_PATTERN = re.compile( r"^" r"(?P<cla>[0-9a-f]{2})?(?P<ins>[0-9a-f]{2})(?P<params>[0-9a-f]{4})?" r"(?::(?P<body>(?:[0-9a-f]{2})+))?" r"(?P<check>=(?P<sw>[0-9a-f]{4})?)?" r"$", re.IGNORECASE, ) def _hex(data: bytes) -> str: return " ".join(f"{d:02X}" for d in data) def _parse_apdu(data: str) -> Tuple[Tuple[int, int, int, int, bytes], Optional[int]]: m = APDU_PATTERN.match(data) if not m: raise ValueError("Invalid APDU format: " + data) cla = int(m.group("cla") or "00", 16) ins = int(m.group("ins"), 16) params = int(m.group("params") or "0000", 16) body = a2b_hex(m.group("body") or "") if m.group("check"): sw: Optional[int] = int(m.group("sw") or "9000", 16) else: sw = None p1, p2 = params >> 8, params & 0xFF return (cla, ins, p1, p2, body), sw def _print_response(resp: bytes, sw: int, no_pretty: bool) -> None: click.echo(f"RECV (SW={sw:04X})" + (":" if resp else "")) if no_pretty: click.echo(resp.hex().upper()) else: for i in range(0, len(resp), 16): chunk = resp[i : i + 16] click.echo( " ".join(f"{c:02X}" for c in chunk).ljust(50) # Replace non-printable characters with a dot. + "".join(chr(c) if 31 < c < 127 else chr(183) for c in chunk) ) @click_command(connections=[SmartCardConnection], hidden="--full-help" not in sys.argv) @click.pass_context @click.option( "-x", "--no-pretty", is_flag=True, help="print only the hex output of a response" ) @click.option( "-a", "--app", type=EnumChoice(AID), required=False, help="select application", ) @click.argument("apdu", nargs=-1) @click.option("-s", "--send-apdu", multiple=True, help="provide full APDUs") def apdu(ctx, no_pretty, app, apdu, send_apdu): """ Execute arbitary APDUs. Provide APDUs as a hex encoded, space-separated list using the following syntax: [CLA]INS[P1P2][:DATA][=EXPECTED_SW] If not provided CLA, P1 and P2 are all set to zero. Setting EXPECTED_SW will cause the command to check the response SW an fail if it differs. "=" can be used as shorthand for "=9000" (SW=OK). Examples: \b Select the OATH application, send a LIST instruction (0xA1), and make sure we get sw=9000 (these are equivalent): $ ykman apdu a40400:a000000527210101=9000 a1=9000 or $ ykman apdu -a oath a1= \b Factory reset the OATH application: $ ykman apdu -a oath 04dead or $ ykman apdu a40400:a000000527210101 04dead or (using full-apdu mode) $ ykman apdu -s 00a4040008a000000527210101 -s 0004dead """ if apdu and send_apdu: ctx.fail("Cannot mix positional APDUs and -s/--send-apdu.") elif not send_apdu: apdus = [_parse_apdu(data) for data in apdu] if not apdus and not app: ctx.fail("No commands provided.") dev = ctx.obj["device"] with dev.open_connection(SmartCardConnection) as conn: protocol = SmartCardProtocol(conn) is_first = True if app: is_first = False click.echo("SELECT AID: " + _hex(app)) resp = protocol.select(app) _print_response(resp, SW.OK, no_pretty) if send_apdu: # Compatibility mode (full APDUs) for apdu in send_apdu: if not is_first: click.echo() else: is_first = False apdu = a2b_hex(apdu) click.echo("SEND: " + _hex(apdu)) resp, sw = protocol.connection.send_and_receive(apdu) _print_response(resp, sw, no_pretty) else: # Standard mode for apdu, check in apdus: if not is_first: click.echo() else: is_first = False header, body = apdu[:4], apdu[4] req = _hex(struct.pack(">BBBB", *header)) if body: req += " -- " + _hex(body) click.echo("SEND: " + req) try: resp = protocol.send_apdu(*apdu) sw = SW.OK except ApduError as e: resp = e.data sw = e.sw _print_response(resp, sw, no_pretty) if check is not None and sw != check: raise CliFail(f"Aborted due to error (expected SW={check:04X}).")
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/apdu.py
apdu.py
from yubikit.core.smartcard import ApduError, SW, SmartCardConnection from yubikit.openpgp import OpenPgpSession, UIF, PIN_POLICY, KEY_REF as _KEY_REF from ..util import parse_certificates, parse_private_key from ..openpgp import get_openpgp_info from .util import ( CliFail, click_force_option, click_format_option, click_postpone_execution, click_prompt, click_group, EnumChoice, pretty_print, ) from enum import IntEnum import logging import click logger = logging.getLogger(__name__) class KEY_REF(IntEnum): SIG = 0x01 DEC = 0x02 AUT = 0x03 ATT = 0x81 ENC = 0x02 # Alias for backwards compatibility, will be removed in ykman 6 def __getattribute__(self, name: str): return _KEY_REF(self).__getattribute__(name) def _fname(fobj): return getattr(fobj, "name", fobj) @click_group(connections=[SmartCardConnection]) @click.pass_context @click_postpone_execution def openpgp(ctx): """ Manage the OpenPGP application. Examples: \b Set the retries for PIN, Reset Code and Admin PIN to 10: $ ykman openpgp access set-retries 10 10 10 \b Require touch to use the authentication key: $ ykman openpgp keys set-touch aut on """ dev = ctx.obj["device"] conn = dev.open_connection(SmartCardConnection) ctx.call_on_close(conn.close) ctx.obj["session"] = OpenPgpSession(conn) @openpgp.command() @click.pass_context def info(ctx): """ Display general status of the OpenPGP application. """ session = ctx.obj["session"] click.echo("\n".join(pretty_print(get_openpgp_info(session)))) @openpgp.command() @click_force_option @click.pass_context def reset(ctx, force): """ Reset all OpenPGP data. This action will wipe all OpenPGP data, and set all PINs to their default values. """ force or click.confirm( "WARNING! This will delete all stored OpenPGP keys and data and restore " "factory settings. Proceed?", abort=True, err=True, ) click.echo("Resetting OpenPGP data, don't remove the YubiKey...") ctx.obj["session"].reset() logger.info("OpenPGP application data reset") click.echo("Success! All data has been cleared and default PINs are set.") echo_default_pins() def echo_default_pins(): click.echo("PIN: 123456") click.echo("Reset code: NOT SET") click.echo("Admin PIN: 12345678") @openpgp.group("access") def access(): """Manage PIN, Reset Code, and Admin PIN.""" @access.command("set-retries") @click.argument("user-pin-retries", type=click.IntRange(1, 99), metavar="PIN-RETRIES") @click.argument( "reset-code-retries", type=click.IntRange(1, 99), metavar="RESET-CODE-RETRIES" ) @click.argument( "admin-pin-retries", type=click.IntRange(1, 99), metavar="ADMIN-PIN-RETRIES" ) @click.option("-a", "--admin-pin", help="admin PIN for OpenPGP") @click_force_option @click.pass_context def set_pin_retries( ctx, admin_pin, user_pin_retries, reset_code_retries, admin_pin_retries, force ): """ Set the number of retry attempts for the User PIN, Reset Code, and Admin PIN. """ session = ctx.obj["session"] if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) resets_pins = session.version < (4, 0, 0) if resets_pins: click.echo("WARNING: Setting PIN retries will reset the values for all 3 PINs!") if force or click.confirm( f"Set PIN retry counters to: {user_pin_retries} {reset_code_retries} " f"{admin_pin_retries}?", abort=True, err=True, ): session.verify_admin(admin_pin) session.set_pin_attempts( user_pin_retries, reset_code_retries, admin_pin_retries ) logger.info("Number of PIN/Reset Code/Admin PIN retries set") if resets_pins: click.echo("Default PINs are set.") echo_default_pins() @access.command("change-pin") @click.option("-P", "--pin", help="current PIN code") @click.option("-n", "--new-pin", help="a new PIN") @click.pass_context def change_pin(ctx, pin, new_pin): """ Change the User PIN. The PIN has a minimum length of 6, and supports any type of alphanumeric characters. """ session = ctx.obj["session"] if pin is None: pin = click_prompt("Enter PIN", hide_input=True) if new_pin is None: new_pin = click_prompt( "New PIN", hide_input=True, confirmation_prompt=True, ) session.change_pin(pin, new_pin) @access.command("change-reset-code") @click.option("-a", "--admin-pin", help="Admin PIN") @click.option("-r", "--reset-code", help="a new Reset Code") @click.pass_context def change_reset_code(ctx, admin_pin, reset_code): """ Change the Reset Code. The Reset Code has a minimum length of 6, and supports any type of alphanumeric characters. """ session = ctx.obj["session"] if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) if reset_code is None: reset_code = click_prompt( "New Reset Code", hide_input=True, confirmation_prompt=True, ) session.verify_admin(admin_pin) session.set_reset_code(reset_code) @access.command("change-admin-pin") @click.option("-a", "--admin-pin", help="current Admin PIN") @click.option("-n", "--new-admin-pin", help="new Admin PIN") @click.pass_context def change_admin(ctx, admin_pin, new_admin_pin): """ Change the Admin PIN. The Admin PIN has a minimum length of 8, and supports any type of alphanumeric characters. """ session = ctx.obj["session"] if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) if new_admin_pin is None: new_admin_pin = click_prompt( "New Admin PIN", hide_input=True, confirmation_prompt=True, ) session.change_admin(admin_pin, new_admin_pin) @access.command("unblock-pin") @click.option( "-a", "--admin-pin", help='admin PIN (use "-" as a value to prompt for input)' ) @click.option("-r", "--reset-code", help="Reset Code") @click.option("-n", "--new-pin", help="a new PIN") @click.pass_context def unblock_pin(ctx, admin_pin, reset_code, new_pin): """ Unblock the PIN (using Reset Code or Admin PIN). If the PIN is lost or blocked you can reset it to a new value using either the Reset Code OR the Admin PIN. The new PIN has a minimum length of 6, and supports any type of alphanumeric characters. """ session = ctx.obj["session"] if reset_code is not None and admin_pin is not None: raise CliFail( "Invalid options: Only one of --reset-code and --admin-pin may be used." ) if admin_pin == "-": admin_pin = click_prompt("Enter Admin PIN", hide_input=True) if reset_code is None and admin_pin is None: reset_code = click_prompt("Enter Reset Code", hide_input=True) if new_pin is None: new_pin = click_prompt( "New PIN", hide_input=True, confirmation_prompt=True, ) if admin_pin: session.verify_admin(admin_pin) session.reset_pin(new_pin, reset_code) @access.command("set-signature-policy") @click.argument("policy", metavar="POLICY", type=EnumChoice(PIN_POLICY)) @click.option("-a", "--admin-pin", help="Admin PIN for OpenPGP") @click.pass_context def set_signature_policy(ctx, policy, admin_pin): """ Set the Signature PIN policy. The Signature PIN policy is used to control whether the PIN is always required when using the Signature key, or if it is required only once per session. \b POLICY signature PIN policy to set (always, once) """ session = ctx.obj["session"] if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) try: session.verify_admin(admin_pin) session.set_signature_pin_policy(policy) except Exception: raise CliFail("Failed to set new Signature PIN policy") @openpgp.group("keys") def keys(): """Manage private keys.""" @keys.command("set-touch") @click.argument("key", metavar="KEY", type=EnumChoice(KEY_REF)) @click.argument("policy", metavar="POLICY", type=EnumChoice(UIF)) @click.option("-a", "--admin-pin", help="Admin PIN for OpenPGP") @click_force_option @click.pass_context def set_touch(ctx, key, policy, admin_pin, force): """ Set the touch policy for OpenPGP keys. The touch policy is used to require user interaction for all operations using the private key on the YubiKey. The touch policy is set individually for each key slot. To see the current touch policy, run the "openpgp info" subcommand. Touch policies: \b Off (default) no touch required On touch required Fixed touch required, can't be disabled without deleting the private key Cached touch required, cached for 15s after use Cached-Fixed touch required, cached for 15s after use, can't be disabled without deleting the private key \b KEY key slot to set (sig, dec, aut or att) POLICY touch policy to set (on, off, fixed, cached or cached-fixed) """ session = ctx.obj["session"] policy_name = policy.name.lower().replace("_", "-") if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) prompt = f"Set touch policy of {key.name} key to {policy_name}?" if policy.is_fixed: prompt = ( "WARNING: This touch policy cannot be changed without deleting the " + "corresponding key slot!\n" + prompt ) if force or click.confirm(prompt, abort=True, err=True): try: session.verify_admin(admin_pin) session.set_uif(key, policy) logger.info(f"Touch policy for slot {key.name} set") except ApduError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: raise CliFail("Touch policy not allowed.") raise CliFail("Failed to set touch policy.") @keys.command("import") @click.option("-a", "--admin-pin", help="Admin PIN for OpenPGP") @click.pass_context @click.argument("key", metavar="KEY", type=EnumChoice(KEY_REF)) @click.argument("private-key", type=click.File("rb"), metavar="PRIVATE-KEY") def import_key(ctx, key, private_key, admin_pin): """ Import a private key (ONLY SUPPORTS ATTESTATION KEY). Import a private key for OpenPGP attestation. \b PRIVATE-KEY file containing the private key (use '-' to use stdin) """ session = ctx.obj["session"] if key != KEY_REF.ATT: ctx.fail("Importing keys is only supported for the Attestation slot.") if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) try: private_key = parse_private_key(private_key.read(), password=None) except Exception: raise CliFail("Failed to parse private key.") try: session.verify_admin(admin_pin) session.put_key(key, private_key) logger.info(f"Private key imported for slot {key.name}") except Exception: raise CliFail("Failed to import attestation key.") @keys.command() @click.pass_context @click.option("-P", "--pin", help="PIN code") @click_format_option @click.argument("key", metavar="KEY", type=EnumChoice(KEY_REF, hidden=[KEY_REF.ATT])) @click.argument("certificate", type=click.File("wb"), metavar="CERTIFICATE") def attest(ctx, key, certificate, pin, format): """ Generate an attestation certificate for a key. Attestation is used to show that an asymmetric key was generated on the YubiKey and therefore doesn't exist outside the device. \b KEY key slot to attest (sig, dec, aut) CERTIFICATE file to write attestation certificate to (use '-' to use stdout) """ session = ctx.obj["session"] if not pin: pin = click_prompt("Enter PIN", hide_input=True) try: cert = session.get_certificate(key) except ValueError: cert = None if not cert or click.confirm( f"There is already data stored in the certificate slot for {key.value}, " "do you want to overwrite it?" ): touch_policy = session.get_uif(KEY_REF.ATT) if touch_policy in [UIF.ON, UIF.FIXED]: click.echo("Touch the YubiKey sensor...") try: session.verify_pin(pin) cert = session.attest_key(key) certificate.write(cert.public_bytes(encoding=format)) logger.info( f"Attestation certificate for slot {key.name} written to " f"{_fname(certificate)}" ) except Exception: raise CliFail("Attestation failed") @openpgp.group("certificates") def certificates(): """ Manage certificates. """ @certificates.command("export") @click.pass_context @click.argument("key", metavar="KEY", type=EnumChoice(KEY_REF)) @click_format_option @click.argument("certificate", type=click.File("wb"), metavar="CERTIFICATE") def export_certificate(ctx, key, format, certificate): """ Export an OpenPGP certificate. \b KEY key slot to read from (sig, dec, aut, or att) CERTIFICATE file to write certificate to (use '-' to use stdout) """ session = ctx.obj["session"] try: cert = session.get_certificate(key) except ValueError: raise CliFail(f"Failed to read certificate from slot {key.name}") certificate.write(cert.public_bytes(encoding=format)) logger.info(f"Certificate for slot {key.name} exported to {_fname(certificate)}") @certificates.command("delete") @click.option("-a", "--admin-pin", help="Admin PIN for OpenPGP") @click.pass_context @click.argument("key", metavar="KEY", type=EnumChoice(KEY_REF)) def delete_certificate(ctx, key, admin_pin): """ Delete an OpenPGP certificate. \b KEY Key slot to delete certificate from (sig, dec, aut, or att). """ session = ctx.obj["session"] if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) try: session.verify_admin(admin_pin) session.delete_certificate(key) logger.info(f"Certificate for slot {key.name} deleted") except Exception: raise CliFail("Failed to delete certificate.") @certificates.command("import") @click.option("-a", "--admin-pin", help="Admin PIN for OpenPGP") @click.pass_context @click.argument("key", metavar="KEY", type=EnumChoice(KEY_REF)) @click.argument("cert", type=click.File("rb"), metavar="CERTIFICATE") def import_certificate(ctx, key, cert, admin_pin): """ Import an OpenPGP certificate. \b KEY key slot to import certificate to (sig, dec, aut, or att) CERTIFICATE file containing the certificate (use '-' to use stdin) """ session = ctx.obj["session"] if admin_pin is None: admin_pin = click_prompt("Enter Admin PIN", hide_input=True) try: certs = parse_certificates(cert.read(), password=None) except Exception: raise CliFail("Failed to parse certificate.") if len(certs) != 1: raise CliFail("Can only import one certificate.") try: session.verify_admin(admin_pin) session.put_certificate(key, certs[0]) except Exception: raise CliFail("Failed to import certificate")
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/openpgp.py
openpgp.py
from yubikit.core import NotSupportedError from yubikit.core.smartcard import SmartCardConnection from yubikit.piv import ( PivSession, InvalidPinError, KEY_TYPE, MANAGEMENT_KEY_TYPE, OBJECT_ID, SLOT, PIN_POLICY, TOUCH_POLICY, DEFAULT_MANAGEMENT_KEY, ) from yubikit.core.smartcard import ApduError, SW from ..util import ( get_leaf_certificates, parse_private_key, parse_certificates, InvalidPasswordError, ) from ..piv import ( get_piv_info, get_pivman_data, get_pivman_protected_data, pivman_set_mgm_key, pivman_change_pin, derive_management_key, generate_random_management_key, generate_chuid, generate_ccc, check_key, generate_self_signed_certificate, generate_csr, ) from .util import ( CliFail, click_group, click_force_option, click_format_option, click_postpone_execution, click_callback, click_prompt, prompt_timeout, EnumChoice, pretty_print, ) from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.backends import default_backend import click import datetime import logging logger = logging.getLogger(__name__) @click_callback() def click_parse_piv_slot(ctx, param, val): try: return SLOT[val.upper().replace("-", "_")] except KeyError: try: return SLOT(int(val, 16)) except Exception: raise ValueError(val) @click_callback() def click_parse_piv_object(ctx, param, val): if val.upper() == "CCC": return OBJECT_ID.CAPABILITY try: return OBJECT_ID[val.upper().replace("-", "_")] except KeyError: try: return int(val, 16) except Exception: raise ValueError(val) @click_callback() def click_parse_management_key(ctx, param, val): try: key = bytes.fromhex(val) if key and len(key) not in (16, 24, 32): raise ValueError( "Management key must be exactly 16, 24, or 32 bytes " "(32, 48, or 64 hexadecimal digits) long." ) return key except Exception: raise ValueError(val) @click_callback() def click_parse_hash(ctx, param, val): try: return getattr(hashes, val) except AttributeError: raise ValueError(val) click_slot_argument = click.argument("slot", callback=click_parse_piv_slot) click_object_argument = click.argument( "object_id", callback=click_parse_piv_object, metavar="OBJECT" ) click_management_key_option = click.option( "-m", "--management-key", help="the management key", callback=click_parse_management_key, ) click_pin_option = click.option("-P", "--pin", help="PIN code") click_pin_policy_option = click.option( "--pin-policy", type=EnumChoice(PIN_POLICY), default=PIN_POLICY.DEFAULT.name, help="PIN policy for slot", ) click_touch_policy_option = click.option( "--touch-policy", type=EnumChoice(TOUCH_POLICY), default=TOUCH_POLICY.DEFAULT.name, help="touch policy for slot", ) click_hash_option = click.option( "-a", "--hash-algorithm", type=click.Choice(["SHA256", "SHA384", "SHA512"], case_sensitive=False), default="SHA256", show_default=True, help="hash algorithm", callback=click_parse_hash, ) def _fname(fobj): return getattr(fobj, "name", fobj) @click_group(connections=[SmartCardConnection]) @click.pass_context @click_postpone_execution def piv(ctx): """ Manage the PIV application. Examples: \b Generate an ECC P-256 private key and a self-signed certificate in slot 9a: $ ykman piv keys generate --algorithm ECCP256 9a pubkey.pem $ ykman piv certificates generate --subject "CN=yubico" 9a pubkey.pem \b Change the PIN from 123456 to 654321: $ ykman piv access change-pin --pin 123456 --new-pin 654321 \b Reset all PIV data and restore default settings: $ ykman piv reset """ dev = ctx.obj["device"] conn = dev.open_connection(SmartCardConnection) ctx.call_on_close(conn.close) session = PivSession(conn) ctx.obj["session"] = session ctx.obj["pivman_data"] = get_pivman_data(session) @piv.command() @click.pass_context def info(ctx): """ Display general status of the PIV application. """ info = get_piv_info(ctx.obj["session"]) click.echo("\n".join(pretty_print(info))) @piv.command() @click.pass_context @click_force_option def reset(ctx, force): """ Reset all PIV data. This action will wipe all data and restore factory settings for the PIV application on the YubiKey. """ force or click.confirm( "WARNING! This will delete all stored PIV data and restore factory " "settings. Proceed?", abort=True, err=True, ) click.echo("Resetting PIV data...") ctx.obj["session"].reset() click.echo("Success! All PIV data have been cleared from the 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") @piv.group() def access(): """Manage PIN, PUK, and Management Key.""" @access.command("set-retries") @click.pass_context @click.argument("pin-retries", type=click.IntRange(1, 255), metavar="PIN-RETRIES") @click.argument("puk-retries", type=click.IntRange(0, 255), metavar="PUK-RETRIES") @click_management_key_option @click_pin_option @click_force_option def set_pin_retries(ctx, management_key, pin, pin_retries, puk_retries, force): """ Set the number of PIN and PUK retry attempts. NOTE: This will reset the PIN and PUK to their factory defaults. """ session = ctx.obj["session"] _ensure_authenticated( ctx, pin, management_key, require_pin_and_key=True, no_prompt=force ) click.echo("WARNING: This will reset the PIN and PUK to the factory defaults!") force or click.confirm( f"Set the number of PIN and PUK retry attempts to: {pin_retries} " f"{puk_retries}?", abort=True, err=True, ) try: session.set_pin_attempts(pin_retries, puk_retries) click.echo("Default PINs are set:") click.echo("\tPIN:\t123456") click.echo("\tPUK:\t12345678") except Exception: raise CliFail("Setting pin retries failed.") @access.command("change-pin") @click.pass_context @click.option("-P", "--pin", help="current PIN code") @click.option("-n", "--new-pin", help="a new PIN to set") def change_pin(ctx, pin, new_pin): """ Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric PINs are recommended. """ session = ctx.obj["session"] if not pin: pin = _prompt_pin("Enter the current PIN") if not new_pin: new_pin = click_prompt( "Enter the new PIN", default="", hide_input=True, show_default=False, confirmation_prompt=True, ) if not _valid_pin_length(pin): ctx.fail("Current PIN must be between 6 and 8 characters long.") if not _valid_pin_length(new_pin): ctx.fail("New PIN must be between 6 and 8 characters long.") try: pivman_change_pin(session, pin, new_pin) click.echo("New PIN set.") except InvalidPinError as e: attempts = e.attempts_remaining if attempts: raise CliFail("PIN change failed - %d tries left." % attempts) else: raise CliFail("PIN is blocked.") @access.command("change-puk") @click.pass_context @click.option("-p", "--puk", help="current PUK code") @click.option("-n", "--new-puk", help="a new PUK code to set") def change_puk(ctx, puk, new_puk): """ Change the PUK code. If the PIN is lost or blocked it can be reset using a PUK. The PUK must be between 6 and 8 characters long, and supports any type of alphanumeric characters. """ session = ctx.obj["session"] if not puk: puk = _prompt_pin("Enter the current PUK") if not new_puk: new_puk = click_prompt( "Enter the new PUK", default="", hide_input=True, show_default=False, confirmation_prompt=True, ) if not _valid_pin_length(puk): ctx.fail("Current PUK must be between 6 and 8 characters long.") if not _valid_pin_length(new_puk): ctx.fail("New PUK must be between 6 and 8 characters long.") try: session.change_puk(puk, new_puk) click.echo("New PUK set.") except InvalidPinError as e: attempts = e.attempts_remaining if attempts: raise CliFail("PUK change failed - %d tries left." % attempts) else: raise CliFail("PUK is blocked.") @access.command("change-management-key") @click.pass_context @click_pin_option @click.option( "-t", "--touch", is_flag=True, help="require touch on YubiKey when prompted for management key", ) @click.option( "-n", "--new-management-key", help="a new management key to set", callback=click_parse_management_key, ) @click.option( "-m", "--management-key", help="current management key", callback=click_parse_management_key, ) @click.option( "-a", "--algorithm", help="management key algorithm", type=EnumChoice(MANAGEMENT_KEY_TYPE), default=MANAGEMENT_KEY_TYPE.TDES.name, show_default=True, ) @click.option( "-p", "--protect", is_flag=True, help="store new management key on the YubiKey, protected by PIN " "(a random key will be used if no key is provided)", ) @click.option( "-g", "--generate", is_flag=True, help="generate a random management key " "(implied by --protect unless --new-management-key is also given, " "can't be used with --new-management-key)", ) @click_force_option def change_management_key( ctx, management_key, algorithm, pin, new_management_key, touch, protect, generate, force, ): """ Change the management key. Management functionality is guarded by a management key. This key is required for administrative tasks, such as generating key pairs. A random key may be generated and stored on the YubiKey, protected by PIN. """ session = ctx.obj["session"] pivman = ctx.obj["pivman_data"] pin_verified = _ensure_authenticated( ctx, pin, management_key, require_pin_and_key=protect, mgm_key_prompt="Enter the current management key [blank to use default key]", no_prompt=force, ) # Can't combine new key with generate. if new_management_key and generate: ctx.fail("Invalid options: --new-management-key conflicts with --generate") # Touch not supported on NEO. if touch and session.version < (4, 0, 0): raise CliFail("Require touch not supported on this YubiKey.") # If an old stored key needs to be cleared, the PIN is needed. if not pin_verified and pivman.has_stored_key: if pin: _verify_pin(ctx, session, pivman, pin, no_prompt=force) elif not force: click.confirm( "The current management key is stored on the YubiKey" " and will not be cleared if no PIN is provided. Continue?", abort=True, err=True, ) if not new_management_key: if protect or generate: new_management_key = generate_random_management_key(algorithm) if not protect: click.echo(f"Generated management key: {new_management_key.hex()}") elif force: ctx.fail( "New management key not given. Please remove the --force " "flag, or set the --generate flag or the " "--new-management-key option." ) else: try: new_management_key = bytes.fromhex( click_prompt( "Enter the new management key", hide_input=True, confirmation_prompt=True, ) ) except Exception: ctx.fail("New management key has the wrong format.") if len(new_management_key) != algorithm.key_len: raise CliFail( "Management key has the wrong length (expected %d bytes)" % algorithm.key_len ) try: pivman_set_mgm_key( session, new_management_key, algorithm, touch=touch, store_on_device=protect ) except ApduError: raise CliFail("Changing the management key failed.") @access.command("unblock-pin") @click.pass_context @click.option("-p", "--puk", required=False) @click.option("-n", "--new-pin", required=False, metavar="NEW-PIN") def unblock_pin(ctx, puk, new_pin): """ Unblock the PIN (using PUK). """ session = ctx.obj["session"] if not puk: puk = click_prompt("Enter PUK", default="", show_default=False, hide_input=True) if not new_pin: new_pin = click_prompt( "Enter a new PIN", default="", show_default=False, hide_input=True ) try: session.unblock_pin(puk, new_pin) click.echo("PIN unblocked") except InvalidPinError as e: attempts = e.attempts_remaining if attempts: raise CliFail("PIN unblock failed - %d tries left." % attempts) else: raise CliFail("PUK is blocked.") @piv.group() def keys(): """ Manage private keys. """ @keys.command("generate") @click.pass_context @click_management_key_option @click_pin_option @click.option( "-a", "--algorithm", help="algorithm to use in key generation", type=EnumChoice(KEY_TYPE), default=KEY_TYPE.RSA2048.name, show_default=True, ) @click_format_option @click_pin_policy_option @click_touch_policy_option @click_slot_argument @click.argument("public-key-output", type=click.File("wb"), metavar="PUBLIC-KEY") def generate_key( ctx, slot, public_key_output, management_key, pin, algorithm, format, pin_policy, touch_policy, ): """ Generate an asymmetric key pair. The private key is generated on the YubiKey, and written to one of the slots. \b SLOT PIV slot of the private key PUBLIC-KEY file containing the generated public key (use '-' to use stdout) """ session = ctx.obj["session"] _ensure_authenticated(ctx, pin, management_key) public_key = session.generate_key(slot, algorithm, pin_policy, touch_policy) key_encoding = format public_key_output.write( public_key.public_bytes( encoding=key_encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) ) logger.info( f"Private key generated in slot {slot}, public key written to " f"{_fname(public_key_output)}" ) @keys.command("import") @click.pass_context @click_pin_option @click_management_key_option @click_pin_policy_option @click_touch_policy_option @click_slot_argument @click.argument("private-key", type=click.File("rb"), metavar="PRIVATE-KEY") @click.option("-p", "--password", help="password used to decrypt the private key") def import_key( ctx, management_key, pin, slot, private_key, pin_policy, touch_policy, password ): """ Import a private key from file. Write a private key to one of the PIV slots on the YubiKey. \b SLOT PIV slot of the private key PRIVATE-KEY file containing the private key (use '-' to use stdin) """ session = ctx.obj["session"] data = private_key.read() while True: if password is not None: password = password.encode() try: private_key = parse_private_key(data, password) except InvalidPasswordError: logger.debug("Error parsing key", exc_info=True) if password is None: password = click_prompt( "Enter password to decrypt key", default="", hide_input=True, show_default=False, ) continue else: password = None click.echo("Wrong password.") continue break _ensure_authenticated(ctx, pin, management_key) session.put_key(slot, private_key, pin_policy, touch_policy) @keys.command() @click.pass_context @click_format_option @click_slot_argument @click.argument("certificate", type=click.File("wb"), metavar="CERTIFICATE") def attest(ctx, slot, certificate, format): """ Generate an attestation certificate for a key pair. Attestation is used to show that an asymmetric key was generated on the YubiKey and therefore doesn't exist outside the device. \b SLOT PIV slot of the private key CERTIFICATE file to write attestation certificate to (use '-' to use stdout) """ session = ctx.obj["session"] try: cert = session.attest_key(slot) except ApduError: raise CliFail("Attestation failed.") certificate.write(cert.public_bytes(encoding=format)) logger.info( f"Attestation certificate for slot {slot} written to {_fname(certificate)}" ) @keys.command("info") @click.pass_context @click_slot_argument def metadata(ctx, slot): """ Show metadata about a private key. This will show what type of key is stored in a specific slot, whether it was imported into the YubiKey, or generated on-chip, and what the PIN and Touch policies are for using the key. \b SLOT PIV slot of the private key """ session = ctx.obj["session"] try: metadata = session.get_slot_metadata(slot) info = { "Key slot": slot, "Algorithm": metadata.key_type.name, "Origin": "GENERATED" if metadata.generated else "IMPORTED", "PIN required for use": metadata.pin_policy.name, "Touch required for use": metadata.touch_policy.name, } click.echo("\n".join(pretty_print(info))) except ApduError as e: if e.sw == SW.REFERENCE_DATA_NOT_FOUND: raise CliFail(f"No key stored in slot {slot}.") raise e @keys.command() @click.pass_context @click_format_option @click_slot_argument @click.option( "-v", "--verify", is_flag=True, help="verify that the public key matches the private key in the slot", ) @click.option("-P", "--pin", help="PIN code (used for --verify)") @click.argument("public-key-output", type=click.File("wb"), metavar="PUBLIC-KEY") def export(ctx, slot, public_key_output, format, verify, pin): """ Export a public key corresponding to a stored private key. This command uses several different mechanisms for exporting the public key corresponding to a stored private key, which may fail. If a certificate is stored in the slot it is assumed to contain the correct public key. If this is not the case, the wrong public key will be returned. The --verify flag can be used to verify that the public key being returned matches the private key, by using the slot to create and verify a signature. This may require the PIN to be provided. \b SLOT PIV slot of the private key PUBLIC-KEY file to write the public key to (use '-' to use stdout) """ session = ctx.obj["session"] try: # Prefer metadata if available public_key = session.get_slot_metadata(slot).public_key logger.debug("Public key read from YubiKey") except ApduError as e: if e.sw == SW.REFERENCE_DATA_NOT_FOUND: raise CliFail(f"No key stored in slot {slot}.") raise CliFail(f"Unable to export public key from slot {slot}.") except NotSupportedError: try: # Try attestation public_key = session.attest_key(slot).public_key() logger.debug("Public key read using attestation") except (NotSupportedError, ApduError): try: # Read from stored certificate public_key = session.get_certificate(slot).public_key() logger.debug("Public key read from stored certificate") if verify: # Only needed when read from certificate def do_verify(): with prompt_timeout(timeout=1.0): if not check_key(session, slot, public_key): raise CliFail( "This public key is not tied to the private key in " f"slot {slot}." ) _verify_pin_if_needed(ctx, session, do_verify, pin) except ApduError: raise CliFail(f"Unable to export public key from slot {slot}.") key_encoding = format public_key_output.write( public_key.public_bytes( encoding=key_encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) ) logger.info(f"Public key for slot {slot} written to {_fname(public_key_output)}") @piv.group("certificates") def cert(): """ Manage certificates. """ @cert.command("import") @click.pass_context @click_management_key_option @click_pin_option @click.option("-p", "--password", help="a password may be needed to decrypt the data") @click.option( "-v", "--verify", is_flag=True, help="verify that the certificate matches the private key in the slot", ) @click.option( "-c", "--compress", is_flag=True, help="compresses the certificate before storing" ) @click_slot_argument @click.argument("cert", type=click.File("rb"), metavar="CERTIFICATE") def import_certificate( ctx, management_key, pin, slot, cert, password, verify, compress ): """ Import an X.509 certificate. Write a certificate to one of the PIV slots on the YubiKey. \b SLOT PIV slot of the certificate CERTIFICATE file containing the certificate (use '-' to use stdin) """ session = ctx.obj["session"] data = cert.read() while True: if password is not None: password = password.encode() try: certs = parse_certificates(data, password) except InvalidPasswordError: logger.debug("Error parsing certificate", exc_info=True) if password is None: password = click_prompt( "Enter password to decrypt certificate", default="", hide_input=True, show_default=False, ) continue else: password = None click.echo("Wrong password.") continue break if len(certs) > 1: # If multiple certs, only import leaf. # Leaf is the cert with a subject that is not an issuer in the chain. leafs = get_leaf_certificates(certs) cert_to_import = leafs[0] else: cert_to_import = certs[0] _ensure_authenticated(ctx, pin, management_key) if verify: public_key = cert_to_import.public_key() try: metadata = session.get_slot_metadata(slot) if metadata.pin_policy in (PIN_POLICY.ALWAYS, PIN_POLICY.ONCE): pivman = ctx.obj["pivman_data"] _verify_pin(ctx, session, pivman, pin) if metadata.touch_policy in (TOUCH_POLICY.ALWAYS, TOUCH_POLICY.CACHED): timeout = 0.0 else: timeout = None except ApduError as e: if e.sw == SW.REFERENCE_DATA_NOT_FOUND: raise CliFail("No private key in slot {slot}") raise e except NotSupportedError: timeout = 1.0 def do_verify(): with prompt_timeout(timeout=timeout): if not check_key(session, slot, public_key): raise CliFail( "The public key of the certificate does not match the " f"private key in slot {slot}" ) _verify_pin_if_needed(ctx, session, do_verify, pin) session.put_certificate(slot, cert_to_import, compress) session.put_object(OBJECT_ID.CHUID, generate_chuid()) @cert.command("export") @click.pass_context @click_format_option @click_slot_argument @click.argument("certificate", type=click.File("wb"), metavar="CERTIFICATE") def export_certificate(ctx, format, slot, certificate): """ Export an X.509 certificate. Reads a certificate from one of the PIV slots on the YubiKey. \b SLOT PIV slot of the certificate CERTIFICATE file to write certificate to (use '-' to use stdout) """ session = ctx.obj["session"] try: cert = session.get_certificate(slot) certificate.write(cert.public_bytes(encoding=format)) logger.info(f"Certificate from slot {slot} exported to {_fname(certificate)}") except ApduError as e: if e.sw == SW.FILE_NOT_FOUND: raise CliFail("No certificate found.") else: raise CliFail("Failed reading certificate.") @cert.command("generate") @click.pass_context @click_management_key_option @click_pin_option @click_slot_argument @click.argument("public-key", type=click.File("rb"), metavar="PUBLIC-KEY") @click.option( "-s", "--subject", help="subject for the certificate, as an RFC 4514 string", required=True, ) @click.option( "-d", "--valid-days", help="number of days until the certificate expires", type=click.INT, default=365, show_default=True, ) @click_hash_option def generate_certificate( ctx, management_key, pin, slot, public_key, subject, valid_days, hash_algorithm ): """ Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key must already be present in the corresponding key slot. \b SLOT PIV slot of the certificate PUBLIC-KEY file containing a public key (use '-' to use stdin) """ session = ctx.obj["session"] try: metadata = session.get_slot_metadata(slot) if metadata.touch_policy in (TOUCH_POLICY.ALWAYS, TOUCH_POLICY.CACHED): timeout = 0.0 else: timeout = None except ApduError as e: if e.sw == SW.REFERENCE_DATA_NOT_FOUND: raise CliFail("No private key in slot {slot}") except NotSupportedError: timeout = 1.0 data = public_key.read() public_key = serialization.load_pem_public_key(data, default_backend()) now = datetime.datetime.utcnow() valid_to = now + datetime.timedelta(days=valid_days) if "=" not in subject: # Old style, common name only. subject = "CN=" + subject # This verifies PIN, make sure next action is sign _ensure_authenticated(ctx, pin, management_key, require_pin_and_key=True) try: with prompt_timeout(timeout=timeout): cert = generate_self_signed_certificate( session, slot, public_key, subject, now, valid_to, hash_algorithm ) session.put_certificate(slot, cert) session.put_object(OBJECT_ID.CHUID, generate_chuid()) except ApduError: raise CliFail("Certificate generation failed.") @cert.command("request") @click.pass_context @click_pin_option @click_slot_argument @click.argument("public-key", type=click.File("rb"), metavar="PUBLIC-KEY") @click.argument("csr-output", type=click.File("wb"), metavar="CSR") @click.option( "-s", "--subject", help="subject for the requested certificate, as an RFC 4514 string", required=True, ) @click_hash_option def generate_certificate_signing_request( ctx, pin, slot, public_key, csr_output, subject, hash_algorithm ): """ Generate a Certificate Signing Request (CSR). A private key must already be present in the corresponding key slot. \b SLOT PIV slot of the certificate PUBLIC-KEY file containing a public key (use '-' to use stdin) CSR file to write CSR to (use '-' to use stdout) """ session = ctx.obj["session"] pivman = ctx.obj["pivman_data"] data = public_key.read() public_key = serialization.load_pem_public_key(data, default_backend()) if "=" not in subject: # Old style, common name only. subject = "CN=" + subject try: metadata = session.get_slot_metadata(slot) if metadata.touch_policy in (TOUCH_POLICY.ALWAYS, TOUCH_POLICY.CACHED): timeout = 0.0 else: timeout = None except ApduError as e: if e.sw == SW.REFERENCE_DATA_NOT_FOUND: raise CliFail("No private key in slot {slot}") except NotSupportedError: timeout = 1.0 # This verifies PIN, make sure next action is sign _verify_pin(ctx, session, pivman, pin) try: with prompt_timeout(timeout=timeout): csr = generate_csr(session, slot, public_key, subject, hash_algorithm) except ApduError: raise CliFail("Certificate Signing Request generation failed.") csr_output.write(csr.public_bytes(encoding=serialization.Encoding.PEM)) logger.info(f"CSR for slot {slot} written to {_fname(csr_output)}") @cert.command("delete") @click.pass_context @click_management_key_option @click_pin_option @click_slot_argument def delete_certificate(ctx, management_key, pin, slot): """ Delete a certificate. Delete a certificate from a PIV slot on the YubiKey. \b SLOT PIV slot of the certificate """ session = ctx.obj["session"] _ensure_authenticated(ctx, pin, management_key) session.delete_certificate(slot) session.put_object(OBJECT_ID.CHUID, generate_chuid()) @piv.group("objects") def objects(): """ Manage PIV data objects. Examples: \b Write the contents of a file to data object with ID: abc123: $ ykman piv objects import abc123 myfile.txt \b Read the contents of the data object with ID: abc123 into a file: $ ykman piv objects export abc123 myfile.txt \b Generate a random value for CHUID: $ ykman piv objects generate chuid """ @objects.command("export") @click_pin_option @click.pass_context @click_object_argument @click.argument("output", type=click.File("wb"), metavar="OUTPUT") def read_object(ctx, pin, object_id, output): """ Export an arbitrary PIV data object. \b OBJECT name of PIV data object, or ID in HEX OUTPUT file to write object to (use '-' to use stdout) """ session = ctx.obj["session"] pivman = ctx.obj["pivman_data"] def do_read_object(retry=True): try: output.write(session.get_object(object_id)) logger.info(f"Exported object {object_id} to {_fname(output)}") except ApduError as e: if e.sw == SW.FILE_NOT_FOUND: raise CliFail("No data found.") elif e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED and retry: _verify_pin(ctx, session, pivman, pin) do_read_object(retry=False) else: raise do_read_object() @objects.command("import") @click_pin_option @click_management_key_option @click.pass_context @click_object_argument @click.argument("data", type=click.File("rb"), metavar="DATA") def write_object(ctx, pin, management_key, object_id, data): """ Write an arbitrary PIV object. Write a PIV object by providing the object id. Yubico writable PIV objects are available in the range 5f0000 - 5fffff. \b OBJECT name of PIV data object, or ID in HEX DATA file containing the data to be written (use '-' to use stdin) """ session = ctx.obj["session"] _ensure_authenticated(ctx, pin, management_key) try: session.put_object(object_id, data.read()) except ApduError as e: if e.sw == SW.INCORRECT_PARAMETERS: raise CliFail("Something went wrong, is the object id valid?") raise CliFail("Error writing object") @objects.command("generate") @click_pin_option @click_management_key_option @click.pass_context @click_object_argument def generate_object(ctx, pin, management_key, object_id): """ Generate and write data for a supported data object. \b Supported data objects: "CHUID" (Card Holder Unique ID) "CCC" (Card Capability Container) \b OBJECT name of PIV data object, or ID in HEX """ session = ctx.obj["session"] _ensure_authenticated(ctx, pin, management_key) if OBJECT_ID.CHUID == object_id: session.put_object(OBJECT_ID.CHUID, generate_chuid()) elif OBJECT_ID.CAPABILITY == object_id: session.put_object(OBJECT_ID.CAPABILITY, generate_ccc()) else: ctx.fail("Unsupported object ID for generate.") def _prompt_management_key(prompt="Enter a management key [blank to use default key]"): management_key = click_prompt( prompt, default="", hide_input=True, show_default=False ) if management_key == "": return DEFAULT_MANAGEMENT_KEY try: return bytes.fromhex(management_key) except Exception: raise CliFail("Management key has the wrong format.") def _prompt_pin(prompt="Enter PIN"): return click_prompt(prompt, default="", hide_input=True, show_default=False) def _valid_pin_length(pin): return 6 <= len(pin) <= 8 def _ensure_authenticated( ctx, pin=None, management_key=None, require_pin_and_key=False, mgm_key_prompt=None, no_prompt=False, ): session = ctx.obj["session"] pivman = ctx.obj["pivman_data"] if pivman.has_protected_key and not management_key: _verify_pin(ctx, session, pivman, pin, no_prompt=no_prompt) return True _authenticate(ctx, session, management_key, mgm_key_prompt, no_prompt=no_prompt) if require_pin_and_key: # Ensure verify was the last thing we did _verify_pin(ctx, session, pivman, pin, no_prompt=no_prompt) return True def _verify_pin(ctx, session, pivman, pin, no_prompt=False): if not pin: if no_prompt: raise CliFail("PIN required.") else: pin = _prompt_pin() try: session.verify_pin(pin) if pivman.has_derived_key: with prompt_timeout(): session.authenticate( MANAGEMENT_KEY_TYPE.TDES, derive_management_key(pin, pivman.salt) ) session.verify_pin(pin) # Ensure verify was the last thing we did elif pivman.has_stored_key: pivman_prot = get_pivman_protected_data(session) try: key_type = session.get_management_key_metadata().key_type except NotSupportedError: key_type = MANAGEMENT_KEY_TYPE.TDES with prompt_timeout(): session.authenticate(key_type, pivman_prot.key) session.verify_pin(pin) # Ensure verify was the last thing we did except InvalidPinError as e: attempts = e.attempts_remaining if attempts > 0: raise CliFail(f"PIN verification failed, {attempts} tries left.") else: raise CliFail("PIN is blocked.") except Exception: raise CliFail("PIN verification failed.") def _verify_pin_if_needed(ctx, session, func, pin=None, no_prompt=False): try: return func() except ApduError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: logger.debug("Command failed due to PIN required, verifying and retrying") pivman = ctx.obj["pivman_data"] _verify_pin(ctx, session, pivman, pin, no_prompt) else: raise return func() def _authenticate(ctx, session, management_key, mgm_key_prompt, no_prompt=False): if not management_key: if no_prompt: ctx.fail("Management key required.") else: if mgm_key_prompt is None: management_key = _prompt_management_key() else: management_key = _prompt_management_key(mgm_key_prompt) try: try: key_type = session.get_management_key_metadata().key_type except NotSupportedError: key_type = MANAGEMENT_KEY_TYPE.TDES with prompt_timeout(): session.authenticate(key_type, management_key) except Exception: raise CliFail("Authentication with management key failed.")
yubikey-manager
/yubikey_manager-5.2.0.tar.gz/yubikey_manager-5.2.0/ykman/_cli/piv.py
piv.py
== YubiKey NEO Manager Tool for managing your YubiKey NEO configuration. Connecting multiple keys at once is supported, but only if CCID mode is active for all of them. Entypo pictograms by Daniel Bruce - www.entypo.com [IMPORTANT] ==== Yubico has learned of a security issue with the OpenPGP Card applet project that is used in the YubiKey NEO. This vulnerability applies to you only if you are using OpenPGP, and you have the OpenPGP applet version 1.0.9 or earlier. link:https://developers.yubico.com/ykneo-openpgp/SecurityAdvisory%202015-04-14.html[SecurityAdvisory 2015-04-14] ==== === Installation The recommended way to install this software including dependencies is by using the provided precompiled binaries for your platform. For Windows and OS X (10.7 and above), there are installers available for download https://developers.yubico.com/yubikey-neo-manager/Releases/[here]. For Ubuntu we have a https://launchpad.net/%7eyubico/+archive/ubuntu/stable[custom PPA] containing the https://launchpad.net/%7eyubico/+archive/ubuntu/stable/+packages?field.name_filter=yubikey-neo-manager&field.status_filter=published&field.series_filter=[yubikey-neo-manager] package. === Dependencies YubiKey NEO Manager requires PySide, libykneomgr, yubikey-personalization and libu2f-host. === Running tests Tests can be run using the "nosetests" command, from the python-nose package. Alternatively "python setup.py test" can be used, but this will cause PySide to be compiled from source, requiring the python-dev package. === Building binaries Binaries for Windows and OSX are built using PyInstaller. Get the source release file, yubikey-neo-manager-<version>.tar.gz, and extract it. It should contain a single directory, henceforth refered to as the release directory. When building binaries for Windows or OS X, you will need to include .dll/.dylib files from the libykneomgr, yubikey-personalization, and libu2f-host projects. Create a subdirectory called "lib" in the release directory. Download the correct binary release for your architecture for each of the aforementioned projects from https://developers.yubico.com/ and extract the .dll/.dylib files for each of them together with the included dependencies to the "lib" directory you created previously. ==== Windows For Windows you will need python, PySide, PyCrypto, PyInstaller and Pywin32 installed (32 or 64-bit versions depending on the architecture of the binary your are building). To sign the executable you will need signtool.exe (from the Windows SDK) either copied into the root as well or in a location in your PATH, as well as a certificate in the Windows certificate store that you wish to sign with. Run "pyinstaller.exe resources/neoman.spec" from the main release directory. With NSIS installed, a Windows installer will be built as well. ==== OSX For OSX you need python, pyside, pycrypto, and pyinstaller installed. One way to install these dependencies is by using Homebrew: brew install python brew install pyside pip install PyInstaller pip install pycrypto NOTE: Homebrew will build backwards-incompatible binaries, so the resulting build will not run on an older version of OSX. For building distributable releases you can use MacPorts instead. Run "pyinstaller resources/neoman.spec" from the main release directory. This will create an .app in the dist directory. Sign the code using codesign: codesign -s 'Developer ID Application' dist/YubiKey\ NEO\ Manager.app --deep There is also a project file for use with http://s.sudre.free.fr/Packaging.html[Packages] located at `resources/neoman.pkgproj`. This can be used to create an installer for distribution, which you should sign prior to distribution: packagesbuild resources/neoman.pkgproj productsign --sign 'Developer ID Installer' dist/YubiKey\ NEO\ Manager.pkg dist/yubikey-neo-manager-mac.pkg
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/README
README
from neoman.u2fh import * from ctypes import POINTER, byref, c_uint, c_size_t, create_string_buffer from neoman.device import BaseDevice from neoman.exc import YkNeoMgrError, ModeSwitchError from neoman.model.modes import MODE from neoman.yk4_utils import (parse_tlv_list, YK4_CAPA_TAG, YK4_CAPA1_OTP, YK4_CAPA1_CCID, YK4_CAPA1_U2F) import os def check(status): if status != 0: raise YkNeoMgrError(status) if u2fh_global_init(1 if 'NEOMAN_DEBUG' in os.environ else 0) != 0: raise Exception("Unable to initialize ykneomgr") libversion = u2fh_check_version(None) devs = POINTER(u2fh_devs)() check(u2fh_devs_init(byref(devs))) U2F_VENDOR_FIRST = 0x40 TYPE_INIT = 0x80 U2FHID_PING = TYPE_INIT | 0x01 U2FHID_YUBIKEY_DEVICE_CONFIG = TYPE_INIT | U2F_VENDOR_FIRST U2FHID_YK4_CAPABILITIES = TYPE_INIT | U2F_VENDOR_FIRST + 2 class U2FDevice(BaseDevice): device_type = 'U2F' version = (0, 0, 0) allowed_modes = (True, True, True) def __init__(self, devs, index, mode=MODE.mode_for_flags(False, False, True)): self._devs = devs self._index = index self._mode = mode self._serial = None @property def mode(self): return self._mode @property def serial(self): return self._serial def _sendrecv(self, cmd, data): buf_size = c_size_t(1024) resp = create_string_buffer(buf_size.value) check(u2fh_sendrecv(self._devs, self._index, cmd, data, len(data), resp, byref(buf_size))) return resp.raw[0:buf_size.value] def set_mode(self, mode): data = ('%02x0f0000' % mode).decode('hex') try: self._sendrecv(U2FHID_YUBIKEY_DEVICE_CONFIG, data) self._mode = mode except YkNeoMgrError: raise ModeSwitchError() def list_apps(self): return [] def poll(self): return hasattr(self, '_index') def close(self): if hasattr(self, '_index'): del self._index del self._devs class SKYDevice(U2FDevice): supported = False default_name = 'Security Key by Yubico' class YK4Device(U2FDevice): default_name = 'YubiKey 4' def __init__(self, devs, index, mode): super(YK4Device, self).__init__(devs, index, mode) self._read_capabilities() if self._cap == 0x07: # YK Edge should not allow CCID. self.default_name = 'YubiKey Edge' self.allowed_modes = (True, False, True) def _read_capabilities(self): data = '\0' resp = self._sendrecv(U2FHID_YK4_CAPABILITIES, data) self._cap_data = parse_tlv_list(resp[1:ord(resp[0]) + 1]) self._cap = int(self._cap_data.get(YK4_CAPA_TAG, '0').encode('hex'), 16) self.allowed_modes = ( bool(self._cap & YK4_CAPA1_OTP), bool(self._cap & YK4_CAPA1_CCID), bool(self._cap & YK4_CAPA1_U2F) ) def open_all_devices(): max_index = c_uint() status = u2fh_devs_discover(devs, byref(max_index)) if status == 0: # We have devices! devices = [] resp = create_string_buffer(1024) for index in range(max_index.value + 1): buf_size = c_size_t(1024) if u2fh_get_device_description( devs, index, resp, byref(buf_size)) == 0: if resp.value.startswith('Yubikey NEO'): mode = MODE.mode_for_flags( 'OTP' in resp.value, 'CCID' in resp.value, 'U2F' in resp.value ) devices.append(U2FDevice(devs, index, mode)) elif resp.value.startswith('Yubikey 4'): mode = MODE.mode_for_flags( 'OTP' in resp.value, 'CCID' in resp.value, 'U2F' in resp.value ) devices.append(YK4Device(devs, index, mode)) elif resp.value.startswith('Security Key by Yubico'): devices.append(SKYDevice(devs, index)) return devices else: # No devices! # u2fh_devs_done(devs) pass return []
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/device_u2f.py
device_u2f.py
from ctypes import (Structure, POINTER, c_int, c_uint8, c_uint, c_ubyte, c_char_p) from neoman.yubicommon.ctypes.libloader import load_library _lib = load_library('ykpers-1', '1') def define(name, args, res): try: fn = getattr(_lib, name) fn.argtypes = args fn.restype = res except AttributeError: print "Undefined symbol: %s" % name def error(*args, **kwargs): raise Exception("Undefined symbol: %s" % name) fn = error return fn YK_KEY = type('YK_KEY', (Structure,), {}) YK_STATUS = type('YK_STATUS', (Structure,), {}) YK_TICKET = type('YK_TICKET', (Structure,), {}) YK_CONFIG = type('YK_CONFIG', (Structure,), {}) YK_NAV = type('YK_NAV', (Structure,), {}) YK_FRAME = type('YK_FRAME', (Structure,), {}) YK_NDEF = type('YK_NDEF', (Structure,), {}) YK_DEVICE_CONFIG = type('YK_DEVICE_CONFIG', (Structure,), {}) ykpers_check_version = define('ykpers_check_version', [c_char_p], c_char_p) yk_init = define('yk_init', [], c_int) yk_release = define('yk_release', [], c_int) yk_open_first_key = define('yk_open_first_key', [], POINTER(YK_KEY)) yk_close_key = define('yk_close_key', [POINTER(YK_KEY)], c_int) yk_get_status = define('yk_get_status', [ POINTER(YK_KEY), POINTER(YK_STATUS)], c_int) yk_get_serial = define('yk_get_serial', [ POINTER(YK_KEY), c_uint8, c_uint, POINTER(c_uint)], c_int) yk_write_device_config = define('yk_write_device_config', [POINTER(YK_KEY), POINTER(YK_DEVICE_CONFIG)], c_int) ykds_alloc = define('ykds_alloc', [], POINTER(YK_STATUS)) ykds_free = define('ykds_free', [POINTER(YK_STATUS)], None) ykds_version_major = define('ykds_version_major', [POINTER(YK_STATUS)], c_int) ykds_version_minor = define('ykds_version_minor', [POINTER(YK_STATUS)], c_int) ykds_version_build = define('ykds_version_build', [POINTER(YK_STATUS)], c_int) ykp_alloc_device_config = define('ykp_alloc_device_config', [], POINTER(YK_DEVICE_CONFIG)) ykp_free_device_config = define('ykp_free_device_config', [POINTER(YK_DEVICE_CONFIG)], c_int) ykp_set_device_mode = define('ykp_set_device_mode', [POINTER(YK_DEVICE_CONFIG), c_ubyte], c_int) yk_get_key_vid_pid = define('yk_get_key_vid_pid', [POINTER(YK_KEY), POINTER(c_int), POINTER(c_int)], c_int) yk_get_capabilities = define('yk_get_capabilities', [POINTER(YK_KEY), c_uint8, c_uint, c_char_p], c_int) __all__ = [x for x in globals().keys() if x.lower().startswith('yk')]
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/ykpers.py
ykpers.py
from neoman.ykpers import * from ctypes import byref, c_uint, c_int, c_size_t, create_string_buffer from neoman.exc import ModeSwitchError from neoman.device import BaseDevice from neoman.model.modes import MODE from neoman.yk4_utils import (parse_tlv_list, YK4_CAPA_TAG, YK4_CAPA1_OTP, YK4_CAPA1_CCID, YK4_CAPA1_U2F) if not yk_init(): raise Exception("Unable to initialize ykpers") libversion = ykpers_check_version(None) def read_version(dev): status = ykds_alloc() try: if yk_get_status(dev, status): return ( ykds_version_major(status), ykds_version_minor(status), ykds_version_build(status) ) else: return (0, 0, 0) finally: ykds_free(status) class OTPDevice(BaseDevice): device_type = 'OTP' allowed_modes = (True, False, False) def __init__(self, dev, version): self._dev = dev self._version = version ser = c_uint() if yk_get_serial(dev, 0, 0, byref(ser)): self._serial = ser.value else: self._serial = None self._mode = self._read_mode(dev) self.allowed_modes = (True, True, version >= (3, 3, 0)) def _read_mode(self, dev): vid = c_int() pid = c_int() try: yk_get_key_vid_pid(dev, byref(vid), byref(pid)) mode = 0x0f & pid.value if mode == 1: # mode 1 has PID 0112 and mode 2 has PID 0111 return 2 elif mode == 2: return 1 else: # all others have 011x where x = mode return mode except: # We know we at least have OTP enabled... return MODE.mode_for_flags(True, False, False) @property def mode(self): return self._mode @property def serial(self): return self._serial @property def version(self): return self._version def set_mode(self, mode): if self.version[0] < 3: raise ValueError("Mode Switching requires version >= 3") config = ykp_alloc_device_config() ykp_set_device_mode(config, mode) try: if not yk_write_device_config(self._dev, config): raise ModeSwitchError() finally: ykp_free_device_config(config) self._mode = mode def list_apps(self): return [] def close(self): if hasattr(self, '_dev'): yk_close_key(self._dev) del self._dev class YKStandardDevice(BaseDevice): device_type = 'OTP' supported = False serial = None version = (0, 0, 0) mode = MODE.mode_for_flags(True, False, False) def __init__(self, dev, version): self._dev = dev self._version = version @property def default_name(self): return 'YubiKey %s' % '.'.join(map(str, self._version)) def close(self): if hasattr(self, '_dev'): yk_close_key(self._dev) del self._dev class YKPlusDevice(YKStandardDevice): mode = MODE.mode_for_flags(True, False, True) default_name = 'YubiKey Plus' class YK4Device(OTPDevice): default_name = 'YubiKey 4' def __init__(self, dev, version): super(YK4Device, self).__init__(dev, version) self._read_capabilities() if self._cap == 0x07: # YK Edge should not allow CCID. self.default_name = 'YubiKey Edge' self.allowed_modes = (True, False, True) def _read_mode(self, dev): vid = c_int() pid = c_int() try: yk_get_key_vid_pid(dev, byref(vid), byref(pid)) mode = 0x0f & pid.value return MODE.mode_for_flags(bool(mode & 1), bool(mode & 4), bool(mode & 2)) except: # We know we at least have OTP enabled... return MODE.mode_for_flags(True, False, False) def _read_capabilities(self): buf_size = c_size_t(1024) resp = create_string_buffer(buf_size.value) yk_get_capabilities(self._dev, 0, 0, resp, byref(buf_size)) resp = resp.raw self._cap_data = parse_tlv_list(resp[1:ord(resp[0]) + 1]) self._cap = int(self._cap_data.get(YK4_CAPA_TAG, '0').encode('hex'), 16) self.allowed_modes = ( bool(self._cap & YK4_CAPA1_OTP), bool(self._cap & YK4_CAPA1_CCID), bool(self._cap & YK4_CAPA1_U2F) ) def open_first_device(): dev = yk_open_first_key() if not dev: raise Exception("Unable to open YubiKey NEO!") version = read_version(dev) if version >= (4, 1, 0): return YK4Device(dev, version) elif version >= (4, 0, 0): return YKPlusDevice(dev, version) elif version >= (3, 0, 0): return OTPDevice(dev, version) else: return YKStandardDevice(dev, version)
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/device_otp.py
device_otp.py
from neoman.ykneomgr import * from ctypes import POINTER, byref, c_size_t, create_string_buffer from neoman.device import BaseDevice from neoman.exc import YkNeoMgrError, ModeSwitchError from neoman.yk4_utils import (parse_tlv_list, YK4_CAPA_TAG, YK4_CAPA1_OTP, YK4_CAPA1_CCID, YK4_CAPA1_U2F) import os if ykneomgr_global_init(1 if 'NEOMAN_DEBUG' in os.environ else 0) != 0: raise Exception("Unable to initialize ykneomgr") libversion = ykneomgr_check_version(None) U2F_SELECT_1 = '00a4040008a0000006472f0001'.decode('hex') U2F_SELECT_2 = '00a4040007a0000005271002'.decode('hex') YK4_SELECT_MGMT = '00a4040008a000000527471117'.decode('hex') YK4_GET_CAPA = '001d0000'.decode('hex') class CCIDDevice(BaseDevice): device_type = 'CCID' version = (0, 0, 0) def __init__(self, dev, version=None, dev_str=None): self._dev = dev self._dev_str = dev_str self._key = None self._locked = True self._serial = ykneomgr_get_serialno(dev) or None self._mode = ykneomgr_get_mode(dev) self._version = ( ykneomgr_get_version_major(dev), ykneomgr_get_version_minor(dev), ykneomgr_get_version_build(dev) ) self._supports_u2f = self._has_u2f_applet() self._apps = None self._broken = False def _has_u2f_applet(self): return '\x90\x00' in [self.send_apdu(U2F_SELECT_1)[-2:], self.send_apdu(U2F_SELECT_2)[-2:]] def check(self, status): if status != 0: self._broken = True raise YkNeoMgrError(status) @property def allowed_modes(self): return (True, True, self._supports_u2f) @property def key(self): return self._key @key.setter def key(self, new_key): self._key = new_key @property def locked(self): return self._locked @property def mode(self): return self._mode @property def serial(self): return self._serial def unlock(self): self._locked = True if not self._key: raise ValueError("No transport key provided!") self.check(ykneomgr_authenticate(self._dev, self._key)) self._locked = False def set_mode(self, mode): if ykneomgr_modeswitch(self._dev, mode) != 0: raise ModeSwitchError() self._mode = mode def send_apdu(self, apdu): self._locked = True buf_size = c_size_t(1024) resp = create_string_buffer(buf_size.value) self.check(ykneomgr_send_apdu(self._dev, apdu, len(apdu), resp, byref(buf_size))) return resp.raw[0:buf_size.value] # Deprecated, DO NOT USE! def _list_apps(self, refresh=False): if refresh or self._apps is None: if self.locked: self.unlock() size = c_size_t() self.check(ykneomgr_applet_list(self._dev, None, byref(size))) applist = create_string_buffer(size.value) self.check(ykneomgr_applet_list(self._dev, applist, byref(size))) self._apps = applist.raw.strip('\0').split('\0') return self._apps def delete_app(self, aid): if self.locked: self.unlock() aid_bytes = aid.decode('hex') self.check(ykneomgr_applet_delete(self._dev, aid_bytes, len(aid_bytes))) def install_app(self, path): if self.locked: self.unlock() self.check(ykneomgr_applet_install(self._dev, create_string_buffer(path))) def close(self): if hasattr(self, '_dev'): ykneomgr_done(self._dev) del self._dev class YK4Device(CCIDDevice): default_name = 'YubiKey 4' allowed_modes = (False, False, False) def __init__(self, dev, version, dev_str): super(YK4Device, self).__init__(dev, version, dev_str) self._read_capabilities() if self._cap == 0x07: # YK Edge should not allow CCID. self.default_name = 'YubiKey Edge' self.allowed_modes = (True, False, True) def _read_capabilities(self): self.send_apdu(YK4_SELECT_MGMT) resp = self.send_apdu(YK4_GET_CAPA) resp, status = resp[:-2], resp[-2:] if status != '\x90\x00': resp = '\x00' if self.version == (4, 2, 4): # 4.2.4 has a bug with capabilities. resp = '0301013f'.decode('hex') self._cap_data = parse_tlv_list(resp[1:ord(resp[0]) + 1]) self._cap = int(self._cap_data.get(YK4_CAPA_TAG, '0').encode('hex'), 16) self.allowed_modes = ( bool(self._cap & YK4_CAPA1_OTP), bool(self._cap & YK4_CAPA1_CCID), bool(self._cap & YK4_CAPA1_U2F) ) @property def version(self): return self._version def check(status): if status != 0: raise YkNeoMgrError(status) def create_device(dev, dev_str=None): version = ( ykneomgr_get_version_major(dev), ykneomgr_get_version_minor(dev), ykneomgr_get_version_build(dev) ) if version[0] == 4: return YK4Device(dev, version, dev_str) return CCIDDevice(dev, version, dev_str) def open_first_device(): dev = POINTER(ykneomgr_dev)() check(ykneomgr_init(byref(dev))) try: check(ykneomgr_discover(dev)) except Exception: ykneomgr_done(dev) raise return create_device(dev) def open_all_devices(existing=None): dev = POINTER(ykneomgr_dev)() check(ykneomgr_init(byref(dev))) size = c_size_t() check(ykneomgr_list_devices(dev, None, byref(size))) devlist = create_string_buffer(size.value) check(ykneomgr_list_devices(dev, devlist, byref(size))) names = devlist.raw.strip('\0').split('\0') devices = [] for d in existing or []: if getattr(d, '_dev_str', None) in names: if d._broken: d.close() else: devices.append(d) names.remove(d._dev_str) for name in names: if not dev: dev = POINTER(ykneomgr_dev)() check(ykneomgr_init(byref(dev))) if ykneomgr_connect(dev, create_string_buffer(name)) == 0: devices.append(create_device(dev, name)) dev = None if dev: ykneomgr_done(dev) return devices
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/device_ccid.py
device_ccid.py
from ctypes import (Structure, POINTER, c_int, c_uint, c_uint8, c_char_p, c_size_t) from neoman.yubicommon.ctypes.libloader import load_library _lib = load_library('ykneomgr', '0') ykneomgr_rc = c_int ykneomgr_initflags = c_uint def define(name, args, res=None): fn = getattr(_lib, name) fn.argtypes = args fn.restype = res return fn ykneomgr_check_version = define('ykneomgr_check_version', [c_char_p], c_char_p) ykneomgr_dev = type('ykneomgr_dev', (Structure,), {}) ykneomgr_global_init = define('ykneomgr_global_init', [ykneomgr_initflags], ykneomgr_rc) ykneomgr_global_done = define('ykneomgr_global_done', []) ykneomgr_init = define('ykneomgr_init', [ POINTER(POINTER(ykneomgr_dev))], ykneomgr_rc) ykneomgr_done = define('ykneomgr_done', [POINTER(ykneomgr_dev)]) ykneomgr_list_devices = define('ykneomgr_list_devices', [POINTER(ykneomgr_dev), c_char_p, POINTER(c_size_t)], ykneomgr_rc) ykneomgr_connect = define('ykneomgr_connect', [POINTER(ykneomgr_dev), c_char_p], ykneomgr_rc) ykneomgr_discover = define('ykneomgr_discover', [POINTER(ykneomgr_dev)], ykneomgr_rc) ykneomgr_get_version_major = define('ykneomgr_get_version_major', [POINTER(ykneomgr_dev)], c_uint8) ykneomgr_get_version_minor = define('ykneomgr_get_version_minor', [POINTER(ykneomgr_dev)], c_uint8) ykneomgr_get_version_build = define('ykneomgr_get_version_build', [POINTER(ykneomgr_dev)], c_uint8) ykneomgr_get_mode = define('ykneomgr_get_mode', [POINTER(ykneomgr_dev)], c_uint8) ykneomgr_get_serialno = define('ykneomgr_get_serialno', [POINTER(ykneomgr_dev)], c_uint) ykneomgr_modeswitch = define('ykneomgr_modeswitch', [POINTER(ykneomgr_dev), c_uint8], ykneomgr_rc) ykneomgr_authenticate = define('ykneomgr_authenticate', [POINTER(ykneomgr_dev), c_char_p], ykneomgr_rc) ykneomgr_applet_list = define('ykneomgr_applet_list', [POINTER(ykneomgr_dev), c_char_p, POINTER(c_size_t)], ykneomgr_rc) ykneomgr_applet_delete = define('ykneomgr_applet_delete', [POINTER(ykneomgr_dev), c_char_p, c_size_t], ykneomgr_rc) ykneomgr_applet_install = define('ykneomgr_applet_install', [POINTER(ykneomgr_dev), c_char_p], ykneomgr_rc) ykneomgr_send_apdu = define('ykneomgr_send_apdu', [POINTER(ykneomgr_dev), c_char_p, c_size_t, c_char_p, POINTER(c_size_t)], ykneomgr_rc) __all__ = [x for x in globals().keys() if x.lower().startswith('ykneomgr')]
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/ykneomgr.py
ykneomgr.py
from neoman.model.modes import MODE class BaseDevice(object): @property def default_name(self): return 'YubiKey NEO' @property def supported(self): return True @property def device_type(self): raise NotImplementedError() @property def mode(self): raise NotImplementedError() @property def allowed_modes(self): return (False, False, False) @property def has_ccid(self): return MODE.flags_for_mode(self.mode)[1] @property def serial(self): raise NotImplementedError() @property def version(self): raise NotImplementedError() def __del__(self): if hasattr(self, 'close'): self.close() def __str__(self): return "NEO[mode=%x, serial=%s]" % (self.mode, self.serial) class ResetStateException(Exception): def __init__(self, devs): self.devices = devs def open_all_devices(existing=None): devices = [] # CCID devices try: from neoman.device_ccid import open_all_devices as open_ccid_all for dev in open_ccid_all(existing): devices.append(dev) except Exception: pass # OTP devices (only if no CCIDs were found) if not devices: dev = None try: from neoman.device_otp import (OTPDevice, open_first_device as open_otp) # Close any existing OTP devices as we are going to reopen them. for e_dev in existing: if isinstance(e_dev, OTPDevice): e_dev.close() dev = open_otp() devices.append(dev) except Exception: pass if dev and dev.has_ccid: print "OTP device with CCID, sleep..." # This key should have been picked up as CCID device, # Make sure it gets a change to next time raise ResetStateException(devices) # U2F devices (No CCIDs nor OTPs) if not devices: u2f_devs = [] try: from neoman.device_u2f import open_all_devices as open_u2f_all u2f_devs = open_u2f_all() devices.extend(u2f_devs) except Exception: pass if filter(lambda x: x.has_ccid, u2f_devs): print "U2F device with CCID, sleep..." # This key should have been picked up as CCID device, # Make sure it gets a change to next time raise ResetStateException(devices) return devices
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/device.py
device.py
# Resource object code # # Created: Thu Nov 12 10:26:36 2015 # by: The Resource Compiler for PySide (Qt v4.8.4) # # WARNING! All changes made in this file will be lost! from PySide import QtCore qt_resource_data = "\x00\x00\x01\xcc\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xde\x03\x13\x0a0\x13\xb7\x83\xa7\xa5\x00\x00\x00\x1diTXtComment\x00\x00\x00\x00\x00Created with GIMPd.e\x07\x00\x00\x010IDAT8\xcb\xcd\xd21K\x9bq\x10\xc7\xf1ObH\x09\xcf\x10t\x08\xe4\xa9\x06\x0a%89\xd9J\xc0\xa1\xa3o \xb3P\xe8\xec\x1bp\x11|\x01]upV\xe2\x9aIp\xc9\xd2\xa1K;D\x9a.\xad\xda\xff\x10\xa4\xa1\xa0qJ\xd2!\x8f\x81H\x12\x92\xcd\xdfx\xbf\xbb\xef\xddq\x97\xb2\xa8\x822\xeax\x8b\xc3E\x8b\xdf\x08\xfe\x08\x06\x82o\x82\xf5\xcc\x93W\xadV\x07\xb3j\xfbK}\x97\xd7\x97:\xa5\x8eB\xab\xa0]nW\xc4\xba\xe9y\x9b\xb7>\xb4tJ\x1d\xd1]\xa4rR!\xd6\x85\xcc\xf3\xc4Z\xad\x96\x9a0z\x09MD\x9b\xa7\x9b\xb2\x8f\xd9\x915\xef\x04\xfb\x88p^\xf8Y\x183\xc6\x00\xdd|\x97 \xff\xac\xfb\x1av\xd1K@\x93\x01\x0f+\x0f\xea\x07\xf5aI\xf0Y\xf0*\xb1>!\x8b3\xb1\x1fS\x01\xb9\x7f9\xc5f\x11r\xd8CCP\xc4\xc7$\xe5h\xd2n#@\xba\x97\xb6}\xbc\x0d\xef\xf1\x0b\xef\xf0\x05\xaf\xf1\x1b\x8d\x99\x80\x91b_\xb1\x85\x16JI\xf4Bl0\x1f`\x08ic\x07\xf7I\xe4j\xdayR\xb3>\xf1v\xe3\x96\x14\xcb7\xcb\xa2\xbf\xd1\xc4\x7f\xc9\xcc:\xfe\xea\xf7U/_\xff\x01b\x88P\x1b\xd1\xc6\xe2Q\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x00\xd5\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xde\x03\x13\x0a1%a\x22\x03}\x00\x00\x00\x1diTXtComment\x00\x00\x00\x00\x00Created with GIMPd.e\x07\x00\x00\x009IDAT8\xcbc`\x18h\xc0\x08c\x84\x86\x86\xfe'E\xe3\xea\xd5\xab\x19\x19\x18\x18\x18\x98(u\x01\x0b.\x93q\x01t\x97R\xec\x82Q\x03\x06\x83\x01,\x84\xe2\x99\xe6.\x18x\x00\x00r\x01\x0a\x1a]I8\xe0\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x02\x05\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x14\x00\x00\x00\x14\x08\x06\x00\x00\x00\x8d\x89\x1d\x0d\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xde\x09\x10\x0b#6\xc4\xaf\xef\x08\x00\x00\x00\x1diTXtComment\x00\x00\x00\x00\x00Created with GIMPd.e\x07\x00\x00\x01iIDAT8\xcb\xb5\x95\xafo\xc2@\x14\xc7?\x05\x048,\x0apmBR;\xc7M\xd5\xb2\xff`K0S\xb0\xbf\xa0\xb9\xbf`C\xeeO\x98\x1a\xa2\xe6\xd48\x8f\xc1\x81b(pW\x81\x84d\x86v\x0di\xef\x96\x90=\xd5w\xf7\xbdO\xde\x8f\xbcW\x0f\x87\xc5q,\x8a\xbe\x94ra\xd3{\x16\xc8\x04\x18U\xbc\x9b\x03\xb32\xb8W\x02{\x05\xa6\xfc\xcd\xde\xa4\x94/\x95\xc08\x8e?-QU\xd9\x5cJ\xf9\x909\xf5\xab\xc8\x1e\xcb^\x04A\xc0x<f0\x18\xb0\x5c.\xaf\xaf}!D[k\xad\x00j\x85\x9aU\xa6\x19\x86!\xcdf\xd3\x16\xe54k^\xe3r0\xb1\xa9\x95Rl6\x1b\xd6\xeb\xb5M6\x01\x16\x19\xd0Z7c\x0c\xc6\x18W-G\x00\xde%\xd4\xaf*U\xab\xd5\xc2\xf7}\xc20D)\xc5~\xbf\xb7A\xef\x1b\xb6\xdb~\xbf\xcfp8\xa4\xd7\xeb\x01\xb8\xeaH\xde\x94*K\xd3\x14\xadu\xeeo\xb7\xdb\xdb\x80\xc6\x18\xba\xdd.\x80\xab!\xbf@\xd7lf\xe9\xeev;'LJ\xb9\xa8\x15f\xd3\x0a<\x1c\x0e\x04A`\x9d\x98b\xca\xb32E\xa7\xd3\xc9\xbf\xa3(\x22MS\x1bp\x96\x8f\x9e\xd6\xfa[\x08\xd1\x06\xee\x8a\x8a\xf3\xf9\xcc\xe9tb\xb5Z\x91$\x09\xc7\xe3\xd1\xb6$\xde\xffw9\x5c\x22\xfd(\x8b\xd4\xb1\xbe\x9e\x8a\x07\xf5k\x85\xd6Z\x09!4\xd0\x06|K\x03\x9e\xb34\x9d\x1b\xfb\x96_\xc0\x0fs\x8b\x87\xf4\xd2\xd9\xef\x13\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x01\xb4\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xde\x03\x13\x0a1\x15G\xfb3\xd1\x00\x00\x00\x1diTXtComment\x00\x00\x00\x00\x00Created with GIMPd.e\x07\x00\x00\x01\x18IDAT8\xcb\xcd\xd2\xbb/C\x01\x14\xc7\xf1\xcf\xd5\xdb\xdc\x96H\xb4\xe3\x0d\x12\x83\x18\xec\x12b\xb0X\xbb\xf5\xef\x90\x18\xfdK\x1d\xed\x161\xf8\x13\xc4\x84\xb8\x22\x1a\x09Z-m]\x83\xebz\xf4\x91\xda\x9c\xf1<\xbe\xe7w\x1e\x81\xbfZb\x0e\x1b\x98\xc3y\xf8\xc7\xe2Yl\xa2\x84G\x5c\x07\x9f\xb1z\xbd\x9eN\xaaM\x83Ts\xa5\xa9W\xee\x89Z\x91\xa3\xfd\xa3Pl03m\xf3v\xb5\xadW\xee\x09_C\x95\xab\x0a\xb1\x01\x0c\x8d\xd0h4\x82\x11\xd2\xcb\xd8A\xa1vP;\x9cy\xfb\xea;\xad\x82U\x14p\x13\xb5\xa3\x1f\x81\x1f\x80A8 \xf9\xa5\xea\xa3\xfb\x22R\x9c\xfd&\xe7\x80~\xb1\xefv\xed\x16v%\xd6%yl9\xcbK\xc4Zc\x01\x85~A\xe9\xa9$\x93\xba\x82-\x89\x08KY\xca\xc5\xa8\xd9r@\x90\x06\xaa\x97U8\xc63\x16\xb0\x9d\xdd\xbc#v?\x11\x90[\xec\x01'h\xa3\x9cy\xef\xc6mw\xf4\x15b/8E?\xf3\xb4\xc6\x01\x86\xfe \xff\xc8=\xba\xf3]i\x90*v\x8a\xc2z8\x1d\xe0\xbbeK\xfd\xe7\xf6\x0e\x8f\x03I%d\x5c\x96\xd0\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x00\xe1<RCC>\x0a<qresource>\x0a<file>icon_about.png</file>\x0a<file>neoman.png</file>\x0a<file>icon_installed.png</file>\x0a<file>qt_resources.qrc</file>\x0a<file>icon_some_installed.png</file>\x0a<file>icon_not_installed.png</file>\x0a</qresource>\x0a</RCC>\x0a\x00\x00\x09R\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x000\x00\x00\x000\x08\x06\x00\x00\x00W\x02\xf9\x87\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xde\x0a\x0e\x0b9/\xe7\x8f\xe7o\x00\x00\x00\x1diTXtComment\x00\x00\x00\x00\x00Created with GIMPd.e\x07\x00\x00\x08\xb6IDATh\xde\xc5\x9amlS\xe7\x15\xc7\x7f\xf7\xda\xb1\x89\xf3B^L\xb2\x94\x10')I\x03\x1d/\xa5\xa5I \x14\xe7\xcb\x90h\xd9P\xa5\xee\x1d4Qi\xd3\xb4\x0f\xdb:WUU\x98T!\xfa\xa12H\x93\xa6IU\xa5\x22\x15iUWib\xeb\xba\xa9l\xab\x03iF\x15\xc2\xebX\x03\x09\x858$,$!\xc1\x8e\x13'\xf6}\xd9\x87<\x09\xbe\xbe\xd7\x8e\x1d\xdc\xee\xe4S\xec{\xcfs\xces\xces\xce\xff\xfc\x1fK\xe4P\xfc\x1d\xed\x0e`\x05\xe0\x04lI_\xab\xc0\x1c0\xeb\xf3\x06b\xb9ZS\xca\x81\xd1%\xc03\xc0\x16\xa0\x09\xa8\x03V\x03\xc5\x09\xfau \x0c\x0c\x03\xb7\x80k@\x0f\xd0\xe5\xf3\x06&\xff/\x0e\xf8;\xda\xeb\x81\x83\xc0nal~\x96*\xa2\xc0\x14\xf0\x11\xf0\xba\xcf\x1b\x08~%\x0e\xf8;\xda\xd7\x00\xaf\x02?%\xb7\xf2\x16\xf0\x06p\xdb\xe7\x0d\xe89w\xc0\xdf\xd1^\x08\xbc\x04\xfc\x1c(\xe3\xcb\x91\x09\xe07\xc01\x9f7\x10\xc9\x99\x03\xfe\x8e\xf6J\xe0\xaf\x22\xcf\xd3\x8a\xaekhh\xe8\xba&R\x7f~\x19I\x92\x91\x91\x91$9\x93%/\x02\xbb}\xde\xc0\xc8C;\xe0\xefh\xdf\x0c\x9c\x03\xec\x96\x06\xa3#\x01\x0e\x9b\x0b\x87\xdd\x85\xdbUGeQ#e.\x0f\xf9y\xc5\xf3\xc9\x1e\x0f31\x13\xe4n\xa4\x9f\xb1\xe9\x9b\xc4\x95\x19b\xea\x0c\xfa\xbck\xa9\x96\x8e\x01O\xfb\xbc\x81\xcb\xcbv\xc0\xdf\xd1\xfeM\xe0\x0f\xa2,\x9aLW\xb4\x18\x95\x85\x8d4\xacj\xc3S\xba\x95\xaa\xa2u\xd8\xe4\xbc\xb4\x1b\xa2\xe9\x0aw\xc2\xbd\x04'\xce\xd1?\xde\xc9H\xa4\x8f<\xd9\x91\xca\x94Y\xe0{>o\xe0d\xd6\x0e\x88\x9d\xff\xcc\xcaxMW\xb1I6v5\xbdBC\xf9\x0e\x1cv\xd7\xb2\x12>\xa6\xce\xd0?v\x86\x8f\xaf\xbf\x89\xaa\xab\xc8\x92-U$\x9a}\xde\xc0\xa5\x8c\x1d\x109?\x94*m\xaaWn`\xef\xd7\x8f\xe0\xb4\x17\xe6\xe4\xe4\xce*\x11N^=\xc8p\xe8J\xaaG\xe2\xc0\x1a\x9f7pwI\x07D\xb59m>\xb0:\xaa\xa6\xb0\xad\xeeG\xb4\xd6\xec_2U\xb2\x15MW8\x1b|\x97\xae\x81\xe3\xd8$\xbb\x95i=\x80\xd7\xe7\x0dL'~hU\x12^\xb2\xaa6\xaa\xa6\xf0\xdc\xfa_\xd3V\xfbb\xce\x8d\x07\x90%;\xdbk\x0f\xf0\xec\xbaC\xa8\xbab\xf5\xc8S\x80/m\x04D\x93\xbadU\xe7\x9b=?\xa0\xad\xf6E\xc39\xd0t\xd5\xb4\x8aM\xceKWYP\xb5\x18\xba\xc9x\x19Yz\x90\xad]\x03\xc7\xf9,x\xc2\xea\xf5\x10\xb0\xd1\xe7\x0d\x0c.|\x90\x9c\xe3\xaf&\x1b\xaf\xe9*5%\x9bi\xad\xd9ox\xf0\xbf\xe1\xcf\xe9\xbe\xfd\x1e6\xe9A4\x14m\x8e\xe6\x9a\xef\xb3z\xe5FK\xe3#\xb1q\xfe\xdew\xcc\xf0\x8e\xaa+lzd\x0f\xf5e-\x8b\x9f\xb5x\xf61\x14\xba\xcc\xe0\xe4\xc5\xe4\x83\xbd\x12x\x0d\xf8\x89)\x02\x02\xdb|\x91\x9c\xf7\x12\x12?\xdb\xfeg\xd3\x81\xd5t\x0d\x7f\xc7\xce\xf9\x05\xa4y5\x9a\x16\xa7\xae\xbc\x85\x176\xfa-\x1d8\x1b<\xc1\xe9/~\x87\xdd\xb6b\xa1\xeb\xa1\xe81~\xf5\xcc?\xc9\xb3\x19\xa1\xd4\x9c2\xc5o\xbb\xbe%\x9a\xa1)\xa2\xb5\x0b\xd8)\xf1\x0c\x1cL~J\xd1b\xecjz\xc5\xb2\xda\xc8\x92\xcc\x96\xea\xe7Qu\x05I\xfc\xd9d\x077\xc6?%\x1a\x0fY:pi\xf8\x8f\xd8e\xe7\xe2\xf3\x9a\xae\xb0\xa9j\x8f\xc9x\x00\xa7\xbd\x88]\x8d/\xa3h\x96\xc8\xfb5\xc3!\x16\x90xwr\x87\xad,l\xa4\xa1|G\xca|\xde\xb2\xfayQ1\x1e\x88]v\xd0}\xfb\xf7\xa6g\x87BW\x08\xcd\x8e\x18\xa0\x84$\xd9x\xb2\xfa\x85\x94\xfa\x1b+\xbcT\x146\xa0\x9bN\x0d{\xfc\x1d\xed\xc5\x89\x11xF@b\xc3\xe9nX\xd5\x96\xb6I\x159+XS\xfa\x84a\x01Y\xb2s}\xf44\xaa\x167<{~\xe8\x03\xec\xb2\xd3\xb0A5%\x9b)\xcd_\x9dR\xbf\xc3\x96\xcfc\xabvZ\x95\x84\x95\xc2\xe6E\x07\xb6$\xe3y\x87\xcd\x85\xa7tk\xda\xd2\x97g\xcb\xa7\xbe\xac\xc5Tu\xa2\xf1\x10\xc1\xc9\xf3\x09\xff\xdfg(\xf4o\xe3\xee#Q_\xdej\x99>\x89\xe2)\xdd\x8a\xc3f\xda\xc4|QV\x91\xc5\x18\xd8d\xf2\xde\xee\xa2\xaah\xdd\x92\xf5\xbb\xbe\xbc\x05\x87\xbd\xc0\xd86\xb5Y\x06&\xcf\x09D\x0a\xc1\xc9\x0b\xc4\x95\x99\xa4\x1c/`\xad{\xc7\x92\xfa\xab\x8a\x9bL\xfa\x85\xac\xf7w\xb4;e1\xc3\xd6%Cb\xb7\xab.\xa3\x86U\xee\xf2PQ\xb8v\xd1\xd8\x05\x19\x98\xe8fN\x9dF\xd3U\x06\xef_0\x1cF]\xd7x\xa4xC\xda\xf4ILIwA\x9dI?P\x0f\xac\x90\x05X3h\xd2\xd0\xa8,j\xcc\xb8\x8b>\xbd\xe6\xbb\xa8z\xdc\x90\x1ew#7\xb87\x1d$\xa6N\x13\x9c\xe8A\x92\xa4\x84\xda\x1f\xa7\xb5\xf6\x87\x19\xeb\xaf,jD\xc3\xe4\xc0j\xc0!\x0b\xf6\xa089\x02e.O\xc6\x0b\xd4\x955S\x92\xbf\xda\xb0K6\xc9N\xcf\xed\xf7\x99\x98\x19\xe4\xde\xcc\xe0b-\xd7t\x95\xaa\xa2&\xaa\x8a\xd6g\xac\xbf,\xbf\xc6*\x02\xc5\x80]\xb6\x06u\xfa\xe20\x92\xa9\xb4z\xf6\x13\xd7\xe6\x0c\x90\xe2\xc6\xbd\x7f\xf1\xe9\xadw\x0c\xa9\xa8hsl\xab=\x90\x95\xee\x15\xf6\xc2\x84\xe9\xce\x88\xe3dr$\x0d\xee6\x0a\x1de\xa6\xa1gp\xf2B\x02\x1c\xd0)s\xd5P\xbdrC\xee@`\x02oc\xe8\x02\xd1x8+EN{!\x8f\xba\xb7\x99B\x9dX:u\xa0\xc1\xbd#\xeb9bN\x89X\xc1\x09m\xc1\x01U\x90N\x86E'f\xb2\xa3id\xc9N]i3v\xd9\x91\xb61=Z\xbe-\xd3\xc1~Q\xeeE\x07\xad\xde\x09\x03\x8a,\xe8\xbeacXd\xeeF\xfa\xb3\x0eg]ys\xda\xb3S\xe8t\xe3)}2k\xbd\xa3S\xfd\xc8\xe6l\x1f\x02b\xb2\x18\x9co%G`l\xfa&\x9a\xf5`\x91\xe6\xb0\x15QW\xdej9'(\xda\x1c[\xab\xbf\x9d\xb5\xf1\xaa\xae06}\xd3*\x02\xb7\x80YY\x10\xad\xd7LC\xa82\xc3\x9dpo\xd6\x0b\xb6z\xf6\x19z\xc2\x02\xeeq\xd8]l\xa8z.k}#\xe1^b\xca\xb4\xd5W\xbd>o`NN\x987\xa3\xc9\x8cAp\xe2\x5c\xd6\x0b\xde\x09\x7f\x8e\x94\x14nU\x8b\xd1R\xb3oYU&8\xd9\xc3\x9c:c\xc5\xabv'V\xa1.A\xb4\x1a*F\xffx'1\xf3\xcbi\xa5{\xf0=\x13\x04q\xda\x0bY_\xf9\x8d\xac\x8d\x8f\xabQ\xae\x8f\x9d\xb6\xfa*\x0ct.: (\xee\x8f\x8c\x85Tb$\xd2G\xff\xd8\x99\x8c\x17\xbc}\xff2\x93\xd1!\x03:\xd5u\x8d\xda\xd2\xad\x148\xb2\xa7S\xaf\x8d~\xc2h\xa4\xdfj\xc6\xfe\xd0\xe7\x0d\x84\x93\x1b\xd9\xeb&\xb8,;\xf8\xf8\xfa\x9b\xcc*K\xf3\xac::7\xc6;M\xf9j\x93\xf3X\xebnK[^\xad\xb9\xa2)N\xf5\x1dM\xf5\xdea\x13\xad\x22f\xcc\xb7\x92\x1b\x9a\xaa\xab\x9c\xbczp\xc9\x8a\x14S\xa6\xe9\x1f\xef4\x80\xb6\xc5\x06W\xbe-k\x8e\xe8\xe4\xd5C\xa2\x9a\x99v\xff\xedDV\x22\xb96\xbd!(\xee\x84\x06ec8t\x85\xb3\xc1w\xd3.\xda;\xfa\x0fF\x22}\xc4\xd4(1u\x9e\xbc\x8d*a\xd6\xba\xdb\xb2\xc6Ug\x83'\x18\x0e]\xb1\xa2\x1aC\xc0\x11\xc3\x08\x9b\x9c\xc6\x82\x9f7\xa5S\xd7\xc0qJ\xf2\xaby<\xc5alp\xef\xe0\x17m\x7f3%V\x81\xc3\x9d\x95\xf1\xff\xb9{\x8a\xae\x81w\x0c\xd4K\x82\x1cK\xbe\xc9IE-\x9e\x01\x9e0Q\x8b\xba\xc2\xf6\xda\x03\xb4x\xf6\x99\x86\xf9\xdcP\x8b'\x84\xf1\x96\xd4\xe2y`g2\xb5\x98\x8a\xdc\xfd\x1a\x10\x04,OPu\xc9F\xf6>~\x18\xa7\xbd(G\xe4\xee\x14'\xaf\x1eJG\xee\xc6\x80\x9a\x8c\xc8\xdd\x04'6\x09z}\x85\x15\xbd.K6v5\xbeLc\x85\x17\x87-\x7fY\x86\xc7\xd5(\xd7F?\xe1T\xdf\xd1E\x9dV`\x14h\xf5y\x03\x17\xb3\xba\x1f\x10N\xec\x05\xde\xb7\x8e\xc4\xfc\x05GEa\x03\x8f\xad\xda9\x7f\xc1Q\xdcd\xe08Sa\x9b\x91p/\xc1\xc9\x1e\xae\x8f\x9df4\xd2/J\xa5\x94\xca\xf8\xef\xf8\xbc\x81?\xa5\xd2\x97\xe9\x15S7\x90\x97\xaa\xfe?\xb8b*\xc0] \xae\x98\xf2k\xc4$5\x8f\xe7\xefE\x07\x19\x9d\x9a\xbfb\x8a)\xd3\x8b\xf0`\x89+\xa6\x96T;\x9f\xb1\x03\xc2\x89J\xe0/\x0b\x5cL\xda\x86\x96\x9bK\xbe\xf3\xc0\xb3V9\xbf,\x07\x84\x13\x05\x82\x9f\xff\xa5`\xc6\xbe\x0c\x09\x01\xc7\x80\xa3\xc9\xd5\xe6\xa1\x1dHp\xa4F\x90\xab?\xce\xb1\xf1o\x03G\xb2\xbd\xb1\x7f\x98\x9f\x1ax\x84#{DD\x96\xf3S\x830\xf0!p8\x11\x1e|%\x0e$8R,\x88\xd6\xa7\x80\xf5\x821[\xf8\xb1\x87\x9c0\x80\x87\xc5\x18x\x0b\xe8\x15\x85\xa1s\x01U.W\xa4\x5c\xe6\x80\xbf\xa3\xdd)\xfa\x86\xc3\x02\xa6(\xa2\xb2\xcc\xfa\xbc\x81\xb9\x5c\xad\xf9?\xb4\xddFJx\xea]\xf1\x00\x00\x00\x00IEND\xaeB`\x82" qt_resource_name = "\x00\x12\x09\xeb\xb6g\x00i\x00c\x00o\x00n\x00_\x00i\x00n\x00s\x00t\x00a\x00l\x00l\x00e\x00d\x00.\x00p\x00n\x00g\x00\x16\x03\xa0mG\x00i\x00c\x00o\x00n\x00_\x00n\x00o\x00t\x00_\x00i\x00n\x00s\x00t\x00a\x00l\x00l\x00e\x00d\x00.\x00p\x00n\x00g\x00\x0e\x02\x0f\xe3\x87\x00i\x00c\x00o\x00n\x00_\x00a\x00b\x00o\x00u\x00t\x00.\x00p\x00n\x00g\x00\x17\x0b\xf7\xc0g\x00i\x00c\x00o\x00n\x00_\x00s\x00o\x00m\x00e\x00_\x00i\x00n\x00s\x00t\x00a\x00l\x00l\x00e\x00d\x00.\x00p\x00n\x00g\x00\x10\x08X\xa8#\x00q\x00t\x00_\x00r\x00e\x00s\x00o\x00u\x00r\x00c\x00e\x00s\x00.\x00q\x00r\x00c\x00\x0a\x03\x8f\xcf\x87\x00n\x00e\x00o\x00m\x00a\x00n\x00.\x00p\x00n\x00g" qt_resource_struct = "\x00\x00\x00\x00\x00\x02\x00\x00\x00\x06\x00\x00\x00\x01\x00\x00\x00\x5c\x00\x00\x00\x00\x00\x01\x00\x00\x02\xa9\x00\x00\x00\xd8\x00\x00\x00\x00\x00\x01\x00\x00\x07O\x00\x00\x00*\x00\x00\x00\x00\x00\x01\x00\x00\x01\xd0\x00\x00\x00\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x06j\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00~\x00\x00\x00\x00\x00\x01\x00\x00\x04\xb2" def qInitResources(): QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) def qCleanupResources(): QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) qInitResources()
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/qt_resources.py
qt_resources.py
otp_u2f_disabled = "OTP and U2F modes cannot currently both be active." organization = "Yubico" domain = "yubico.com" app_name = "YubiKey NEO Manager" win_title_1 = "YubiKey NEO Manager (%s)" ok = "OK" cancel = "Cancel" wait = "Please wait..." welcome = "Welcome" welcome_desc = "No device found.\n\n\n" \ "Please insert a YubiKey to continue..." note_1 = "NOTE: %s" overview = "Overview" otp = "OTP" ccid = "CCID" otp_ccid = "OTP+CCID" u2f = "U2F" otp_u2f = "OTP+U2F" u2f_ccid = "U2F+CCID" otp_u2f_ccid = "OTP+U2F+CCID" ccid_touch_eject = "CCID with touch eject" requires_ccid = "Requires CCID mode" settings = "Settings" change_name = "Change name" change_name_desc = "Change the name of the device." manage_keys = "Manage transport keys" key_required = "Transport key required" key_required_desc = "Managing apps on this YubiKey requires a password" change_mode = "Change connection mode" change_mode_1 = "Change connection mode [%s]" change_mode_desc = ("Set the connection mode used by your YubiKey.\nFor " "this setting to take effect, you will need to unplug, " "and re-attach your YubiKey.") remove_device = "\nRemove your YubiKey now.\n" mode_note = ("To be able to list/manage apps, your YubiKey must have CCID " "enabled.") mode_error = "Error setting mode" mode_error_desc = "Failed setting the mode. If you have an Access Code " \ "protecting either of the YubiKey slots, you will need to disable this " \ "before you can change the mode." name = "Name" name_1 = "Name: %s" serial_1 = "Serial: %s" firmware_1 = "Firmware version: %s" u2f_1 = "U2F/FIDO: %s" u2f_supported = "supported" u2f_not_supported_1 = "<a href=\"%s\">not supported</a>" aid_1 = "AID: %s" status_1 = "Status: %s" version_1 = "Version: %s" latest_version_1 = "Latest version: %s" download = "Download" downloading_file = "Downloading file..." install = "Install" installed = "Installed" installed_1 = "%s installed" installing = "Installing applet" installing_1 = "Installing applet: %s" error_installing = "Error installing applet" error_installing_1 = "There was an error installing the applet: %s" error_uninstalling = "Error uninstalling applet" error_uninstalling_1 = "There was an error uninstalling the applet: %s" error_downloading = "Error downloading applet" error_downloading_1 = "There was an error downloading the applet: %s" not_installed = "Not installed" uninstall = "Uninstall" delete_app_confirm = "Delete applet?" delete_app_desc = ("WARNING! Deleting an applet removes ALL associated data, " "including credentials, and this data will NOT be " "recoverable.") deleting_1 = "Deleting applet: %s" install_cap = "Install applet from CAP file" select_cap = "Select a CAP file" devices = "Devices" apps = "Available apps" installed_apps = "Installed apps" unknown = "Unknown" unknown_applet = "Unknown applet" unsupported_device = "The %s doesn't support this device." % app_name about_1 = "About: %s" libraries = "Library versions" about_link_1 = "For help and discussion, see our <a href=\"%s\">forum</a>." copyright = "Copyright &copy; Yubico" def _translate(qt): values = globals() for key, value in values.items(): if isinstance(value, basestring) and not key.startswith('_'): values[key] = qt.tr(value)
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/messages.py
messages.py
from __future__ import absolute_import from PySide import QtCore from collections import MutableMapping __all__ = ['Settings', 'PySettings', 'convert_to'] def convert_to(value, target_type): if target_type is list: return [] if value is None else [value] if target_type is int: return 0 if value in ['', 'false', 'False'] else int(value) if target_type is float: return float(value) if target_type is bool: return value not in ['', 'false', 'False'] return value.encode('utf8') class SettingsGroup(object): def __init__(self, settings, mutex, group): self._settings = settings self._mutex = mutex self._group = group def __getattr__(self, method_name): if hasattr(self._settings, method_name): fn = getattr(self._settings, method_name) def wrapped(*args, **kwargs): try: self._mutex.lock() self._settings.beginGroup(self._group) return fn(*args, **kwargs) finally: self._settings.endGroup() self._mutex.unlock() return wrapped def rename(self, new_name): data = dict((key, self.value(key)) for key in self.childKeys()) self.remove('') self._group = new_name for k, v in data.items(): self.setValue(k, v) def __repr__(self): return 'Group(%s)' % self._group class Settings(QtCore.QObject): def __init__(self, q_settings, wrap=True): super(Settings, self).__init__() self._mutex = QtCore.QMutex(QtCore.QMutex.Recursive) self._wrap = wrap self._q_settings = q_settings def get_group(self, group): g = SettingsGroup(self._q_settings, self._mutex, group) if self._wrap: g = PySettings(g) return g @staticmethod def wrap(*args, **kwargs): return Settings(QtCore.QSettings(*args, **kwargs)) class PySettings(MutableMapping): def __init__(self, settings): self._settings = settings def __getattr__(self, method_name): return getattr(self._settings, method_name) def get(self, key, default=None): val = self._settings.value(key, default) if not isinstance(val, type(default)): val = convert_to(val, type(default)) return val def __getitem__(self, key): return self.get(key) def __setitem__(self, key, value): self._settings.setValue(key, value) def __delitem__(self, key): self._settings.remove(key) def __iter__(self): for key in list(self.keys()): yield key def __len__(self): return len(self._settings.childKeys()) def __contains__(self, key): return self._settings.contains(key) def keys(self): return self._settings.childKeys() def update(self, data): for key, value in list(data.items()): self[key] = value def clear(self): self._settings.remove('') def __repr__(self): return 'PySettings(%s)' % self._settings
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/yubicommon/qt/settings.py
settings.py
from __future__ import absolute_import from PySide import QtGui, QtCore from .worker import Worker import os import sys import time import importlib __all__ = ['Application', 'Dialog', 'MutexLocker'] TOP_SECTION = '<b>%s</b>' SECTION = '<br><b>%s</b>' class Dialog(QtGui.QDialog): def __init__(self, *args, **kwargs): super(Dialog, self).__init__(*args, **kwargs) self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint) self._headers = _Headers() @property def headers(self): return self._headers def section(self, title): return self._headers.section(title) class _Headers(object): def __init__(self): self._first = True def section(self, title): if self._first: self._first = False section = TOP_SECTION % title else: section = SECTION % title return QtGui.QLabel(section) class _MainWindow(QtGui.QMainWindow): def __init__(self): super(_MainWindow, self).__init__() self._widget = None def customEvent(self, event): event.callback() event.accept() class Application(QtGui.QApplication): def __init__(self, m=None): super(Application, self).__init__(sys.argv) self.window = _MainWindow() if m: m._translate(self) self.worker = Worker(self.window, m) if getattr(sys, 'frozen', False): # we are running in a PyInstaller bundle self.basedir = sys._MEIPASS else: # we are running in a normal Python environment top_module_str = __package__.split('.')[0] top_module = importlib.import_module(top_module_str) self.basedir = os.path.dirname(top_module.__file__) def ensure_singleton(self, name=None): if not name: name = self.applicationName() from PySide import QtNetwork self._l_socket = QtNetwork.QLocalSocket() self._l_socket.connectToServer(name, QtCore.QIODevice.WriteOnly) if self._l_socket.waitForConnected(): self.worker.thread().quit() self.deleteLater() time.sleep(0.01) # Without this the process sometimes stalls. sys.exit(0) else: self._l_server = QtNetwork.QLocalServer() if not self._l_server.listen(name): QtNetwork.QLocalServer.removeServer(name) self._l_server.listen(name) self._l_server.newConnection.connect(self._show_window) def _show_window(self): self.window.show() self.window.activateWindow() def exec_(self): status = super(Application, self).exec_() self.worker.thread().quit() self.deleteLater() time.sleep(0.01) # Without this the process sometimes stalls. return status class MutexLocker(object): """Drop-in replacement for QMutexLocker that can start unlocked.""" def __init__(self, mutex, lock=True): self._mutex = mutex self._locked = False if lock: self.relock() def lock(self, try_lock=False): if try_lock: self._locked = self._mutex.tryLock() else: self._mutex.lock() self._locked = True return self._locked and self or None def relock(self): self.lock() def unlock(self): if self._locked: self._mutex.unlock() def __del__(self): self.unlock()
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/yubicommon/qt/classes.py
classes.py
from __future__ import absolute_import from PySide import QtGui, QtCore from functools import partial from .utils import get_active_window, default_messages import traceback class _Messages(object): wait = 'Please wait...' class _Event(QtCore.QEvent): EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType()) def __init__(self, callback): super(_Event, self).__init__(_Event.EVENT_TYPE) self._callback = callback def callback(self): self._callback() del self._callback class Worker(QtCore.QObject): _work_signal = QtCore.Signal(tuple) _work_done_0 = QtCore.Signal() @default_messages(_Messages) def __init__(self, window, m): super(Worker, self).__init__() self.window = window self.busy = QtGui.QProgressDialog('', None, 0, 0, window) self.busy.setWindowTitle(m.wait) self.busy.setWindowModality(QtCore.Qt.WindowModal) self.busy.setMinimumDuration(0) self.busy.setWindowFlags(self.busy.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint) self.busy.setAutoClose(True) self.work_thread = QtCore.QThread() self.moveToThread(self.work_thread) self.work_thread.start() self._work_signal.connect(self.work) self._work_done_0.connect(self.busy.reset) def post(self, title, fn, callback=None, return_errors=False): self.busy.setLabelText(title) self.busy.adjustPosition(get_active_window()) self.busy.show() self.post_bg(fn, callback, return_errors) def post_bg(self, fn, callback=None, return_errors=False): if isinstance(fn, tuple): fn = partial(fn[0], *fn[1:]) self._work_signal.emit((fn, callback, return_errors)) def post_fg(self, fn): if isinstance(fn, tuple): fn = partial(fn[0], *fn[1:]) event = _Event(fn) QtGui.QApplication.postEvent(self.window, event) @QtCore.Slot(tuple) def work(self, job): QtCore.QThread.msleep(10) # Needed to yield (fn, callback, return_errors) = job try: result = fn() except Exception as e: traceback.print_exc() result = e if not return_errors: def callback(e): raise e if callback: event = _Event(partial(callback, result)) QtGui.QApplication.postEvent(self.window, event) self._work_done_0.emit()
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/yubicommon/qt/worker.py
worker.py
from __future__ import absolute_import from __future__ import print_function import os import sys import json import errno import pkg_resources from glob import glob VS_VERSION_INFO = """ VSVersionInfo( ffi=FixedFileInfo( # filevers and prodvers should be always a tuple with four # items: (1, 2, 3, 4) # Set not needed items to zero 0. filevers=%(ver_tup)r, prodvers=%(ver_tup)r, # Contains a bitmask that specifies the valid bits 'flags'r mask=0x0, # Contains a bitmask that specifies the Boolean attributes # of the file. flags=0x0, # The operating system for which this file was designed. # 0x4 - NT and there is no need to change it. OS=0x4, # The general type of file. # 0x1 - the file is an application. fileType=0x1, # The function of the file. # 0x0 - the function is not defined for this fileType subtype=0x0, # Creation date and time stamp. date=(0, 0) ), kids=[ StringFileInfo( [ StringTable( u'040904E4', [StringStruct(u'FileDescription', u'%(name)s'), StringStruct(u'FileVersion', u'%(ver_str)s'), StringStruct(u'InternalName', u'%(internal_name)s'), StringStruct(u'LegalCopyright', u'Copyright © 2015 Yubico'), StringStruct(u'OriginalFilename', u'%(exe_name)s'), StringStruct(u'ProductName', u'%(name)s'), StringStruct(u'ProductVersion', u'%(ver_str)s')]) ]), VarFileInfo([VarStruct(u'Translation', [1033, 1252])]) ] )""" data = json.loads(os.environ['pyinstaller_data']) try: data = dict((k, v.encode('ascii') if isinstance(v, unicode) else v) for k, v in data.items()) except NameError: pass # Python 3, encode not needed. dist = pkg_resources.get_distribution(data['name']) ver_str = dist.version DEBUG = bool(data['debug']) NAME = data['long_name'] WIN = sys.platform in ['win32', 'cygwin'] OSX = sys.platform in ['darwin'] file_ext = '.exe' if WIN else '' if WIN: icon_ext = 'ico' elif OSX: icon_ext = 'icns' else: icon_ext = 'png' ICON = os.path.join('resources', '%s.%s' % (data['name'], icon_ext)) if not os.path.isfile(ICON): ICON = None # Generate scripts from entry_points. merge = [] entry_map = dist.get_entry_map() console_scripts = entry_map.get('console_scripts', {}) gui_scripts = entry_map.get('gui_scripts', {}) for ep in list(gui_scripts.values()) + list(console_scripts.values()): script_path = os.path.join(WORKPATH, ep.name + '-script.py') with open(script_path, 'w') as fh: fh.write("import %s\n" % ep.module_name) fh.write("%s.%s()\n" % (ep.module_name, '.'.join(ep.attrs))) merge.append( (Analysis([script_path], [dist.location], None, None, None, None), ep.name, ep.name + file_ext) ) MERGE(*merge) # Read version information on Windows. VERSION = None if WIN: VERSION = 'build/file_version_info.txt' global int_or_zero # Needed due to how this script is invoked def int_or_zero(v): try: return int(v) except ValueError: return 0 ver_tup = tuple(int_or_zero(v) for v in ver_str.split('.')) # Windows needs 4-tuple. if len(ver_tup) < 4: ver_tup += (0,) * (4-len(ver_tup)) elif len(ver_tup) > 4: ver_tup = ver_tup[:4] # Write version info. with open(VERSION, 'w') as f: f.write(VS_VERSION_INFO % { 'name': NAME, 'internal_name': data['name'], 'ver_tup': ver_tup, 'ver_str': ver_str, 'exe_name': NAME + file_ext }) pyzs = [PYZ(m[0].pure) for m in merge] exes = [] for (a, a_name, a_name_ext), pyz in zip(merge, pyzs): exe = EXE(pyz, a.scripts, exclude_binaries=True, name=a_name_ext, debug=DEBUG, strip=None, upx=True, console=DEBUG or a_name in console_scripts, append_pkg=not OSX, version=VERSION, icon=ICON) exes.append(exe) # Sign the executable if WIN: os.system("signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" % (exe.name)) collect = [] for (a, _, a_name), exe in zip(merge, exes): collect += [exe, a.binaries, a.zipfiles, a.datas] # Data files collect.append([(os.path.basename(fn), fn, 'DATA') for fn in data['data_files']]) # DLLs, dylibs and executables should go here. collect.append([(fn[4:], fn, 'BINARY') for fn in glob('lib/*')]) coll = COLLECT(*collect, strip=None, upx=True, name=NAME) # Create .app for OSX if OSX: app = BUNDLE(coll, name="%s.app" % NAME, version=ver_str, icon=ICON) qt_conf = 'dist/%s.app/Contents/Resources/qt.conf' % NAME qt_conf_dir = os.path.dirname(qt_conf) try: os.makedirs(qt_conf_dir) except OSError as e: if not (e.errno == errno.EEXIST and os.path.isdir(qt_conf_dir)): raise with open(qt_conf, 'w') as f: f.write('[Path]\nPlugins = plugins') # Create Windows installer if WIN: installer_cfg = 'resources/win-installer.nsi' if os.path.isfile(installer_cfg): os.system('makensis.exe -D"VERSION=%s" %s' % (ver_str, installer_cfg)) installer = "dist/%s-%s-win.exe" % (data['name'], ver_str) os.system("signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" % (installer)) print("Installer created: %s" % installer)
yubikey-neo-manager
/yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/yubicommon/setup/pyinstaller_spec.py
pyinstaller_spec.py