repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
sangoma/pysensu
pysensu/api.py
SensuAPI.delete_event
python
def delete_event(self, client, check): self._request('DELETE', '/events/{}/{}'.format(client, check)) return True
Resolves an event for a given check on a given client. (delayed action)
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L133-L138
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.post_event
python
def post_event(self, client, check): self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True
Resolves an event. (delayed action)
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L140-L146
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.get_check
python
def get_check(self, check): data = self._request('GET', '/checks/{}'.format(check)) return data.json()
Returns a check.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L158-L163
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.post_check_request
python
def post_check_request(self, check, subscribers): data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True
Issues a check execution request.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L165-L174
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.post_silence_request
python
def post_silence_request(self, kwargs): self._request('POST', '/silenced', data=json.dumps(kwargs)) return True
Create a silence entry.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L191-L196
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.clear_silence
python
def clear_silence(self, kwargs): self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True
Clear a silence entry.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L198-L203
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.get_aggregate_check
python
def get_aggregate_check(self, check, age=None): data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json()
Returns the list of aggregates for a given check
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L215-L225
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.get_health
python
def get_health(self, consumers=2, messages=100): data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False
Returns health information on transport & Redis connections.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L244-L254
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.get_results
python
def get_results(self, client): data = self._request('GET', '/results/{}'.format(client)) return data.json()
Returns a result.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L266-L271
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.get_result
python
def get_result(self, client, check): data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json()
Returns an event for a given client & result name.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L273-L278
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.delete_result
python
def delete_result(self, client, check): self._request('DELETE', '/results/{}/{}'.format(client, check)) return True
Deletes an check result data for a given check on a given client.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L280-L285
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.post_result_data
python
def post_result_data(self, client, check, output, status): data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True
Posts check result data.
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L287-L298
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.create_stash
python
def create_stash(self, payload, path=None): if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True
Create a stash. (JSON document)
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L310-L319
[ "def _request(self, method, path, **kwargs):\n url = '{}{}'.format(self._url_base, path)\n logger.debug('{} -> {} with {}'.format(method, url, kwargs))\n\n if method == 'GET':\n resp = requests.get(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'POST':\n resp = requests.post(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'PUT':\n resp = requests.put(url, auth=self.auth, headers=self._header,\n **kwargs)\n\n elif method == 'DELETE':\n resp = requests.delete(url, auth=self.auth, headers=self._header,\n **kwargs)\n else:\n raise SensuAPIException(\n 'Method {} not implemented'.format(method)\n )\n\n if resp.status_code in self.good_status:\n logger.debug('{}: {}'.format(\n resp.status_code,\n ''.join(resp.text.split('\\n'))[0:80]\n ))\n return resp\n\n elif resp.status_code.startswith('400'):\n logger.error('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API returned \"Bad Request\"')\n\n else:\n logger.warning('{}: {}'.format(\n resp.status_code,\n resp.text\n ))\n raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text))\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.get_subscriptions
python
def get_subscriptions(self, nodes=[]): if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels
Returns all the channels where (optionally specified) nodes are subscribed
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L331-L349
[ "def get_clients(self, limit=None, offset=None):\n \"\"\"\n Returns a list of clients.\n \"\"\"\n data = {}\n if limit:\n data['limit'] = limit\n if offset:\n data['offset'] = offset\n result = self._request('GET', '/clients', data=json.dumps(data))\n return result.json()\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
sangoma/pysensu
pysensu/api.py
SensuAPI.get_subscriptions_channel
python
def get_subscriptions_channel(self, search_channel): data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.append(client['name']) else: if search_channel == client['subscriptions']: clients.append(client['name']) return clients
Return all the nodes that are subscribed to the specified channel
train
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L351-L365
[ "def get_clients(self, limit=None, offset=None):\n \"\"\"\n Returns a list of clients.\n \"\"\"\n data = {}\n if limit:\n data['limit'] = limit\n if offset:\n data['offset'] = offset\n result = self._request('GET', '/clients', data=json.dumps(data))\n return result.json()\n" ]
class SensuAPI(object): def __init__(self, url_base, username=None, password=None): self._url_base = url_base self._header = { 'User-Agent': USER_AGENT } self.good_status = (200, 201, 202, 204) if username and password: self.auth = HTTPBasicAuth(username, password) else: self.auth = None def _request(self, method, path, **kwargs): url = '{}{}'.format(self._url_base, path) logger.debug('{} -> {} with {}'.format(method, url, kwargs)) if method == 'GET': resp = requests.get(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'POST': resp = requests.post(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'PUT': resp = requests.put(url, auth=self.auth, headers=self._header, **kwargs) elif method == 'DELETE': resp = requests.delete(url, auth=self.auth, headers=self._header, **kwargs) else: raise SensuAPIException( 'Method {} not implemented'.format(method) ) if resp.status_code in self.good_status: logger.debug('{}: {}'.format( resp.status_code, ''.join(resp.text.split('\n'))[0:80] )) return resp elif resp.status_code.startswith('400'): logger.error('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API returned "Bad Request"') else: logger.warning('{}: {}'.format( resp.status_code, resp.text )) raise SensuAPIException('API bad response {}: {}'.format(resp.status_code, resp.text)) """ Clients ops """ def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() def delete_client(self, client): """ Removes a client, resolving its current events. (delayed action) """ self._request('DELETE', '/clients/{}'.format(client)) return True """ Events ops """ def get_events(self): """ Returns the list of current events. """ data = self._request('GET', '/events') return data.json() def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True """ Checks ops """ def get_checks(self): """ Returns the list of checks. """ data = self._request('GET', '/checks') return data.json() def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True """ Silenced API ops """ def get_silenced(self, limit=None, offset=None): """ Returns a list of silence entries. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/silenced', data=json.dumps(data)) return result.json() def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True """ Aggregates ops """ def get_aggregates(self): """ Returns the list of named aggregates. """ data = self._request('GET', '/aggregates') return data.json() def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() def delete_aggregate(self, check): """ Deletes all aggregate data for a named aggregate """ self._request('DELETE', '/aggregates/{}'.format(check)) return True """ Status ops """ def get_info(self): """ Returns information on the API. """ data = self._request('GET', '/info') return data.json() def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False """ Results ops """ def get_all_client_results(self): """ Returns the list of results. """ data = self._request('GET', '/results') return data.json() def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True """ Stashes ops """ def get_stashes(self): """ Returns a list of stashes. """ data = self._request('GET', '/stashes') return data.json() def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True def delete_stash(self, path): """ Delete a stash. (JSON document) """ self._request('DELETE', '/stashes/{}'.format(path)) return True """ Subscriptions ops (not directly in the Sensu API) """ def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): for channel in client['subscriptions']: if channel not in channels: channels.append(channel) else: if client['subscriptions'] not in channels: channels.append(client['subscriptions']) return channels
idlesign/srptools
srptools/utils.py
hex_from
python
def hex_from(val): if isinstance(val, integer_types): hex_str = '%x' % val if len(hex_str) % 2: hex_str = '0' + hex_str return hex_str return hexlify(val)
Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/utils.py#L22-L34
null
from __future__ import unicode_literals from binascii import unhexlify, hexlify from base64 import b64encode, b64decode from six import integer_types def value_encode(val, base64=False): """Encodes int into hex or base64.""" return b64_from(val) if base64 else hex_from(val) def hex_from_b64(val): """Returns hex string representation for base64 encoded value. :param str val: :rtype: bytes|str """ return hex_from(b64decode(val)) def int_from_hex(hexstr): """Returns int/long representation for a given hex string. :param bytes|str|unicode hexstr: :rtype: int|long """ return int(hexstr, 16) def int_to_bytes(val): """Returns bytes representation for a given int/long. :param int|long val: :rtype: bytes|str """ hex_str = hex_from(val) return unhexlify(hex_str) def b64_from(val): """Returns base64 encoded bytes for a given int/long/bytes value. :param int|long|bytes val: :rtype: bytes|str """ if isinstance(val, integer_types): val = int_to_bytes(val) return b64encode(val).decode('ascii')
idlesign/srptools
srptools/utils.py
b64_from
python
def b64_from(val): if isinstance(val, integer_types): val = int_to_bytes(val) return b64encode(val).decode('ascii')
Returns base64 encoded bytes for a given int/long/bytes value. :param int|long|bytes val: :rtype: bytes|str
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/utils.py#L56-L64
[ "def int_to_bytes(val):\n \"\"\"Returns bytes representation for a given int/long.\n\n :param int|long val:\n :rtype: bytes|str\n \"\"\"\n hex_str = hex_from(val)\n return unhexlify(hex_str)\n" ]
from __future__ import unicode_literals from binascii import unhexlify, hexlify from base64 import b64encode, b64decode from six import integer_types def value_encode(val, base64=False): """Encodes int into hex or base64.""" return b64_from(val) if base64 else hex_from(val) def hex_from_b64(val): """Returns hex string representation for base64 encoded value. :param str val: :rtype: bytes|str """ return hex_from(b64decode(val)) def hex_from(val): """Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str """ if isinstance(val, integer_types): hex_str = '%x' % val if len(hex_str) % 2: hex_str = '0' + hex_str return hex_str return hexlify(val) def int_from_hex(hexstr): """Returns int/long representation for a given hex string. :param bytes|str|unicode hexstr: :rtype: int|long """ return int(hexstr, 16) def int_to_bytes(val): """Returns bytes representation for a given int/long. :param int|long val: :rtype: bytes|str """ hex_str = hex_from(val) return unhexlify(hex_str)
idlesign/srptools
srptools/context.py
SRPContext.pad
python
def pad(self, val): padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded
:param val: :rtype: bytes
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L64-L71
[ "def int_to_bytes(val):\n \"\"\"Returns bytes representation for a given int/long.\n\n :param int|long val:\n :rtype: bytes|str\n \"\"\"\n hex_str = hex_from(val)\n return unhexlify(hex_str)\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.hash
python
def hash(self, *args, **kwargs): joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest())
:param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L73-L102
[ "def int_from_hex(hexstr):\n \"\"\"Returns int/long representation for a given hex string.\n\n :param bytes|str|unicode hexstr:\n :rtype: int|long\n \"\"\"\n return int(hexstr, 16)\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.generate_random
python
def generate_random(self, bits_len=None): bits_len = bits_len or self._bits_random return random().getrandbits(bits_len)
Generates a random value. :param int bits_len: :rtype: int
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L104-L111
null
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_common_secret
python
def get_common_secret(self, server_public, client_public): return self.hash(self.pad(client_public), self.pad(server_public))
u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L120-L127
[ "def pad(self, val):\n \"\"\"\n :param val:\n :rtype: bytes\n \"\"\"\n padding = len(int_to_bytes(self._prime))\n padded = int_to_bytes(val).rjust(padding, b'\\x00')\n return padded\n", "def hash(self, *args, **kwargs):\n \"\"\"\n :param args:\n :param kwargs:\n joiner - string to join values (args)\n as_bytes - bool to return hash bytes instead of default int\n :rtype: int|bytes\n \"\"\"\n joiner = kwargs.get('joiner', '').encode('utf-8')\n as_bytes = kwargs.get('as_bytes', False)\n\n def conv(arg):\n if isinstance(arg, integer_types):\n arg = int_to_bytes(arg)\n\n if PY3:\n if isinstance(arg, str):\n arg = arg.encode('utf-8')\n return arg\n\n return str(arg)\n\n digest = joiner.join(map(conv, args))\n\n hash_obj = self._hash_func(digest)\n\n if as_bytes:\n return hash_obj.digest()\n\n return int_from_hex(hash_obj.hexdigest())\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_client_premaster_secret
python
def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime)
S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L129-L141
[ "def get_common_password_verifier(self, password_hash):\n \"\"\"v = g^x % N\n\n :param int password_hash:\n :rtype: int\n \"\"\"\n return pow(self._gen, password_hash, self._prime)\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_server_premaster_secret
python
def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime)
S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L151-L160
null
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_server_public
python
def get_server_public(self, password_verifier, server_private): return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime
B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L184-L191
null
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_common_password_hash
python
def get_common_password_hash(self, salt): password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':'))
x = H(s | H(I | ":" | P)) :param int salt: :rtype: int
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L193-L203
[ "def hash(self, *args, **kwargs):\n \"\"\"\n :param args:\n :param kwargs:\n joiner - string to join values (args)\n as_bytes - bool to return hash bytes instead of default int\n :rtype: int|bytes\n \"\"\"\n joiner = kwargs.get('joiner', '').encode('utf-8')\n as_bytes = kwargs.get('as_bytes', False)\n\n def conv(arg):\n if isinstance(arg, integer_types):\n arg = int_to_bytes(arg)\n\n if PY3:\n if isinstance(arg, str):\n arg = arg.encode('utf-8')\n return arg\n\n return str(arg)\n\n digest = joiner.join(map(conv, args))\n\n hash_obj = self._hash_func(digest)\n\n if as_bytes:\n return hash_obj.digest()\n\n return int_from_hex(hash_obj.hexdigest())\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_common_session_key_proof
python
def get_common_session_key_proof(self, session_key, salt, server_public, client_public): h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove
M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L213-L232
[ "def hash(self, *args, **kwargs):\n \"\"\"\n :param args:\n :param kwargs:\n joiner - string to join values (args)\n as_bytes - bool to return hash bytes instead of default int\n :rtype: int|bytes\n \"\"\"\n joiner = kwargs.get('joiner', '').encode('utf-8')\n as_bytes = kwargs.get('as_bytes', False)\n\n def conv(arg):\n if isinstance(arg, integer_types):\n arg = int_to_bytes(arg)\n\n if PY3:\n if isinstance(arg, str):\n arg = arg.encode('utf-8')\n return arg\n\n return str(arg)\n\n digest = joiner.join(map(conv, args))\n\n hash_obj = self._hash_func(digest)\n\n if as_bytes:\n return hash_obj.digest()\n\n return int_from_hex(hash_obj.hexdigest())\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True) def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_common_session_key_proof_hash
python
def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): return self.hash(client_public, session_key_proof, session_key, as_bytes=True)
H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L234-L242
[ "def hash(self, *args, **kwargs):\n \"\"\"\n :param args:\n :param kwargs:\n joiner - string to join values (args)\n as_bytes - bool to return hash bytes instead of default int\n :rtype: int|bytes\n \"\"\"\n joiner = kwargs.get('joiner', '').encode('utf-8')\n as_bytes = kwargs.get('as_bytes', False)\n\n def conv(arg):\n if isinstance(arg, integer_types):\n arg = int_to_bytes(arg)\n\n if PY3:\n if isinstance(arg, str):\n arg = arg.encode('utf-8')\n return arg\n\n return str(arg)\n\n digest = joiner.join(map(conv, args))\n\n hash_obj = self._hash_func(digest)\n\n if as_bytes:\n return hash_obj.digest()\n\n return int_from_hex(hash_obj.hexdigest())\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_user_data_triplet(self, base64=False): """( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple """ salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
idlesign/srptools
srptools/context.py
SRPContext.get_user_data_triplet
python
def get_user_data_triplet(self, base64=False): salt = self.generate_salt() verifier = self.get_common_password_verifier(self.get_common_password_hash(salt)) verifier = value_encode(verifier, base64) salt = value_encode(salt, base64) return self._user, verifier, salt
( <_user>, <_password verifier>, <salt> ) :param base64: :rtype: tuple
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L244-L256
[ "def value_encode(val, base64=False):\n \"\"\"Encodes int into hex or base64.\"\"\"\n return b64_from(val) if base64 else hex_from(val)\n", "def generate_salt(self):\n \"\"\"s = random\n\n :rtype: int\n \"\"\"\n return self.generate_random(self._bits_salt)\n", "def get_common_password_hash(self, salt):\n \"\"\"x = H(s | H(I | \":\" | P))\n\n :param int salt:\n :rtype: int\n \"\"\"\n password = self._password\n if password is None:\n raise SRPException('User password should be in context for this scenario.')\n\n return self.hash(salt, self.hash(self._user, password, joiner=':'))\n", "def get_common_password_verifier(self, password_hash):\n \"\"\"v = g^x % N\n\n :param int password_hash:\n :rtype: int\n \"\"\"\n return pow(self._gen, password_hash, self._prime)\n" ]
class SRPContext(object): """ * The SRP Authentication and Key Exchange System https://tools.ietf.org/html/rfc2945 * Using the Secure Remote Password (SRP) Protocol for TLS Authentication https://tools.ietf.org/html/rfc5054 """ def __init__( self, username, password=None, prime=None, generator=None, hash_func=None, multiplier=None, bits_random=1024, bits_salt=64): """ :param str|unicode username: User name :param str|unicode password: User _password :param str|unicode|None prime: Prime hex string . Default: PRIME_1024 :param str|unicode|None generator: Generator hex string. Default: PRIME_1024_GEN :param str|unicode hash_func: Function to calculate hash. Default: HASH_SHA_1 :param str|unicode multiplier: Multiplier hex string. If not given will be calculated automatically using _prime and _gen. :param int bits_random: Random value bits. Default: 1024 :param int bits_salt: Salt value bits. Default: 64 """ self._hash_func = hash_func or HASH_SHA_1 # H self._user = username # I self._password = password # p self._gen = int_from_hex(generator or PRIME_1024_GEN) # g self._prime = int_from_hex(prime or PRIME_1024) # N self._mult = ( # k = H(N | PAD(g)) int_from_hex(multiplier) if multiplier else self.hash(self._prime, self.pad(self._gen))) self._bits_salt = bits_salt self._bits_random = bits_random @property def generator(self): return hex_from(self._gen) @property def generator_b64(self): return b64_from(self._gen) @property def prime(self): return hex_from(self._prime) @property def prime_b64(self): return b64_from(self._prime) def pad(self, val): """ :param val: :rtype: bytes """ padding = len(int_to_bytes(self._prime)) padded = int_to_bytes(val).rjust(padding, b'\x00') return padded def hash(self, *args, **kwargs): """ :param args: :param kwargs: joiner - string to join values (args) as_bytes - bool to return hash bytes instead of default int :rtype: int|bytes """ joiner = kwargs.get('joiner', '').encode('utf-8') as_bytes = kwargs.get('as_bytes', False) def conv(arg): if isinstance(arg, integer_types): arg = int_to_bytes(arg) if PY3: if isinstance(arg, str): arg = arg.encode('utf-8') return arg return str(arg) digest = joiner.join(map(conv, args)) hash_obj = self._hash_func(digest) if as_bytes: return hash_obj.digest() return int_from_hex(hash_obj.hexdigest()) def generate_random(self, bits_len=None): """Generates a random value. :param int bits_len: :rtype: int """ bits_len = bits_len or self._bits_random return random().getrandbits(bits_len) def generate_salt(self): """s = random :rtype: int """ return self.generate_random(self._bits_salt) def get_common_secret(self, server_public, client_public): """u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int """ return self.hash(self.pad(client_public), self.pad(server_public)) def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """ password_verifier = self.get_common_password_verifier(password_hash) return pow( (server_public - (self._mult * password_verifier)), (client_private + (common_secret * password_hash)), self._prime) def get_common_session_key(self, premaster_secret): """K = H(S) :param int premaster_secret: :rtype: bytes """ return self.hash(premaster_secret, as_bytes=True) def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) def generate_client_private(self): """a = random() :rtype: int """ return self.generate_random() def generate_server_private(self): """b = random() :rtype: int """ return self.generate_random() def get_client_public(self, client_private): """A = g^a % N :param int client_private: :rtype: int """ return pow(self._gen, client_private, self._prime) def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime def get_common_password_hash(self, salt): """x = H(s | H(I | ":" | P)) :param int salt: :rtype: int """ password = self._password if password is None: raise SRPException('User password should be in context for this scenario.') return self.hash(salt, self.hash(self._user, password, joiner=':')) def get_common_password_verifier(self, password_hash): """v = g^x % N :param int password_hash: :rtype: int """ return pow(self._gen, password_hash, self._prime) def get_common_session_key_proof(self, session_key, salt, server_public, client_public): """M = H(H(N) XOR H(g) | H(U) | s | A | B | K) :param bytes session_key: :param int salt: :param int server_public: :param int client_public: :rtype: bytes """ h = self.hash prove = h( h(self._prime) ^ h(self._gen), h(self._user), salt, client_public, server_public, session_key, as_bytes=True ) return prove def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public): """H(A | M | K) :param bytes session_key: :param bytes session_key_proof: :param int client_public: :rtype: bytes """ return self.hash(client_public, session_key_proof, session_key, as_bytes=True)
idlesign/srptools
setup.py
get_version
python
def get_version(): contents = read(os.path.join(PATH_BASE, 'srptools', '__init__.py')) version = re.search('VERSION = \(([^)]+)\)', contents) version = version.group(1).replace(', ', '.').strip() return version
Reads version number. This workaround is required since __init__ is an entry point exposing stuff from other modules, which may use dependencies unavailable in current environment, which in turn will prevent this application from install.
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/setup.py#L16-L28
[ "def read(fpath):\n return io.open(fpath).read()\n" ]
import os import io import re import sys from setuptools import setup, find_packages PATH_BASE = os.path.dirname(__file__) PYTEST_RUNNER = ['pytest-runner'] if 'test' in sys.argv else [] def read(fpath): return io.open(fpath).read() setup( name='srptools', version=get_version(), url='https://github.com/idlesign/srptools', description='Tools to implement Secure Remote Password (SRP) authentication', long_description=read(os.path.join(PATH_BASE, 'README.rst')), license='BSD 3-Clause License', author='Igor `idle sign` Starikov', author_email='idlesign@yandex.ru', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=['six'], setup_requires=[] + PYTEST_RUNNER, extras_require={'cli': ['click>=2.0']}, tests_require=['pytest'], entry_points={'console_scripts': ['srptools = srptools.cli:main']}, test_suite='tests', classifiers=[ # As in https://pypi.python.org/pypi?:action=list_classifiers 'Development Status :: 5 - Production/Stable', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'License :: OSI Approved :: BSD License' ], )
idlesign/srptools
srptools/cli.py
common_options
python
def common_options(func): def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func
Commonly used command options.
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L41-L58
null
from __future__ import division from collections import OrderedDict import click from srptools import VERSION, SRPContext, SRPServerSession, SRPClientSession, hex_from_b64 from srptools.constants import * PRESETS = OrderedDict([ ('1024', (PRIME_1024, PRIME_1024_GEN)), ('1536', (PRIME_1536, PRIME_1536_GEN)), ('2048', (PRIME_2048, PRIME_2048_GEN)), ('3072', (PRIME_3072, PRIME_3072_GEN)), ('4096', (PRIME_4096, PRIME_4096_GEN)), ('6144', (PRIME_6144, PRIME_6144_GEN)), ]) @click.group() @click.version_option(version='.'.join(map(str, VERSION))) def base(): """srptools command line utility. Tools to implement Secure Remote Password (SRP) authentication. Basic scenario: > srptools get_user_data_triplet > srptools server get_private_and_public > srptools client get_private_and_public > srptools client get_session_data > srptools server get_session_data """ @base.group() def server(): """Server session related commands.""" @base.group() def client(): """Client session related commands.""" @server.command() @click.argument('username') @click.argument('password_verifier') @common_options def get_private_and_public(username, password_verifier, private, preset): """Print out server public and private.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) click.secho('Server private: %s' % session.private_b64) click.secho('Server public: %s' % session.public_b64) @server.command() @click.argument('username') @click.argument('password_verifier') @click.argument('salt') @click.argument('client_public') @common_options def get_session_data( username, password_verifier, salt, client_public, private, preset): """Print out server session data.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_public, salt, base64=True) click.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64) @client.command() @click.argument('username') @click.argument('password') @common_options def get_private_and_public(ctx, username, password, private, preset): """Print out server public and private.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) click.secho('Client private: %s' % session.private_b64) click.secho('Client public: %s' % session.public_b64) @client.command() @click.argument('username') @click.argument('password') @click.argument('salt') @click.argument('server_public') @common_options def get_session_data(ctx, username, password, salt, server_public, private, preset): """Print out client session data.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) click.secho('Client session key: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64) @base.command() @click.argument('username') @click.argument('password') def get_user_data_triplet(username, password): """Print out user data triplet: username, password verifier, salt.""" context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password verifier: %s' % password_verifier) click.secho('Salt: %s' % salt) def main(): """ CLI entry point """ base(obj={})
idlesign/srptools
srptools/cli.py
get_private_and_public
python
def get_private_and_public(username, password_verifier, private, preset): session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) click.secho('Server private: %s' % session.private_b64) click.secho('Server public: %s' % session.public_b64)
Print out server public and private.
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L75-L82
[ "def hex_from_b64(val):\n \"\"\"Returns hex string representation for base64 encoded value.\n\n :param str val:\n :rtype: bytes|str\n \"\"\"\n return hex_from(b64decode(val))\n" ]
from __future__ import division from collections import OrderedDict import click from srptools import VERSION, SRPContext, SRPServerSession, SRPClientSession, hex_from_b64 from srptools.constants import * PRESETS = OrderedDict([ ('1024', (PRIME_1024, PRIME_1024_GEN)), ('1536', (PRIME_1536, PRIME_1536_GEN)), ('2048', (PRIME_2048, PRIME_2048_GEN)), ('3072', (PRIME_3072, PRIME_3072_GEN)), ('4096', (PRIME_4096, PRIME_4096_GEN)), ('6144', (PRIME_6144, PRIME_6144_GEN)), ]) @click.group() @click.version_option(version='.'.join(map(str, VERSION))) def base(): """srptools command line utility. Tools to implement Secure Remote Password (SRP) authentication. Basic scenario: > srptools get_user_data_triplet > srptools server get_private_and_public > srptools client get_private_and_public > srptools client get_session_data > srptools server get_session_data """ def common_options(func): """Commonly used command options.""" def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func @base.group() def server(): """Server session related commands.""" @base.group() def client(): """Client session related commands.""" @server.command() @click.argument('username') @click.argument('password_verifier') @common_options @server.command() @click.argument('username') @click.argument('password_verifier') @click.argument('salt') @click.argument('client_public') @common_options def get_session_data( username, password_verifier, salt, client_public, private, preset): """Print out server session data.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_public, salt, base64=True) click.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64) @client.command() @click.argument('username') @click.argument('password') @common_options def get_private_and_public(ctx, username, password, private, preset): """Print out server public and private.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) click.secho('Client private: %s' % session.private_b64) click.secho('Client public: %s' % session.public_b64) @client.command() @click.argument('username') @click.argument('password') @click.argument('salt') @click.argument('server_public') @common_options def get_session_data(ctx, username, password, salt, server_public, private, preset): """Print out client session data.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) click.secho('Client session key: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64) @base.command() @click.argument('username') @click.argument('password') def get_user_data_triplet(username, password): """Print out user data triplet: username, password verifier, salt.""" context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password verifier: %s' % password_verifier) click.secho('Salt: %s' % salt) def main(): """ CLI entry point """ base(obj={})
idlesign/srptools
srptools/cli.py
get_session_data
python
def get_session_data( username, password_verifier, salt, client_public, private, preset): session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_public, salt, base64=True) click.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64)
Print out server session data.
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L91-L101
[ "def hex_from_b64(val):\n \"\"\"Returns hex string representation for base64 encoded value.\n\n :param str val:\n :rtype: bytes|str\n \"\"\"\n return hex_from(b64decode(val))\n", "def process(self, other_public, salt, base64=False):\n salt = self._value_decode(salt, base64)\n other_public = self._value_decode(other_public, base64)\n\n self.init_base(salt)\n self.init_common_secret(other_public)\n self.init_session_key()\n self.init_session_key_proof()\n\n key = value_encode(self._key, base64)\n key_proof = value_encode(self._key_proof, base64)\n key_proof_hash = value_encode(self._key_proof_hash, base64)\n\n return key, key_proof, key_proof_hash\n" ]
from __future__ import division from collections import OrderedDict import click from srptools import VERSION, SRPContext, SRPServerSession, SRPClientSession, hex_from_b64 from srptools.constants import * PRESETS = OrderedDict([ ('1024', (PRIME_1024, PRIME_1024_GEN)), ('1536', (PRIME_1536, PRIME_1536_GEN)), ('2048', (PRIME_2048, PRIME_2048_GEN)), ('3072', (PRIME_3072, PRIME_3072_GEN)), ('4096', (PRIME_4096, PRIME_4096_GEN)), ('6144', (PRIME_6144, PRIME_6144_GEN)), ]) @click.group() @click.version_option(version='.'.join(map(str, VERSION))) def base(): """srptools command line utility. Tools to implement Secure Remote Password (SRP) authentication. Basic scenario: > srptools get_user_data_triplet > srptools server get_private_and_public > srptools client get_private_and_public > srptools client get_session_data > srptools server get_session_data """ def common_options(func): """Commonly used command options.""" def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func @base.group() def server(): """Server session related commands.""" @base.group() def client(): """Client session related commands.""" @server.command() @click.argument('username') @click.argument('password_verifier') @common_options def get_private_and_public(username, password_verifier, private, preset): """Print out server public and private.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) click.secho('Server private: %s' % session.private_b64) click.secho('Server public: %s' % session.public_b64) @server.command() @click.argument('username') @click.argument('password_verifier') @click.argument('salt') @click.argument('client_public') @common_options @client.command() @click.argument('username') @click.argument('password') @common_options def get_private_and_public(ctx, username, password, private, preset): """Print out server public and private.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) click.secho('Client private: %s' % session.private_b64) click.secho('Client public: %s' % session.public_b64) @client.command() @click.argument('username') @click.argument('password') @click.argument('salt') @click.argument('server_public') @common_options def get_session_data(ctx, username, password, salt, server_public, private, preset): """Print out client session data.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) click.secho('Client session key: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64) @base.command() @click.argument('username') @click.argument('password') def get_user_data_triplet(username, password): """Print out user data triplet: username, password verifier, salt.""" context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password verifier: %s' % password_verifier) click.secho('Salt: %s' % salt) def main(): """ CLI entry point """ base(obj={})
idlesign/srptools
srptools/cli.py
get_private_and_public
python
def get_private_and_public(ctx, username, password, private, preset): session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) click.secho('Client private: %s' % session.private_b64) click.secho('Client public: %s' % session.public_b64)
Print out server public and private.
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L108-L115
[ "def hex_from_b64(val):\n \"\"\"Returns hex string representation for base64 encoded value.\n\n :param str val:\n :rtype: bytes|str\n \"\"\"\n return hex_from(b64decode(val))\n" ]
from __future__ import division from collections import OrderedDict import click from srptools import VERSION, SRPContext, SRPServerSession, SRPClientSession, hex_from_b64 from srptools.constants import * PRESETS = OrderedDict([ ('1024', (PRIME_1024, PRIME_1024_GEN)), ('1536', (PRIME_1536, PRIME_1536_GEN)), ('2048', (PRIME_2048, PRIME_2048_GEN)), ('3072', (PRIME_3072, PRIME_3072_GEN)), ('4096', (PRIME_4096, PRIME_4096_GEN)), ('6144', (PRIME_6144, PRIME_6144_GEN)), ]) @click.group() @click.version_option(version='.'.join(map(str, VERSION))) def base(): """srptools command line utility. Tools to implement Secure Remote Password (SRP) authentication. Basic scenario: > srptools get_user_data_triplet > srptools server get_private_and_public > srptools client get_private_and_public > srptools client get_session_data > srptools server get_session_data """ def common_options(func): """Commonly used command options.""" def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func @base.group() def server(): """Server session related commands.""" @base.group() def client(): """Client session related commands.""" @server.command() @click.argument('username') @click.argument('password_verifier') @common_options def get_private_and_public(username, password_verifier, private, preset): """Print out server public and private.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) click.secho('Server private: %s' % session.private_b64) click.secho('Server public: %s' % session.public_b64) @server.command() @click.argument('username') @click.argument('password_verifier') @click.argument('salt') @click.argument('client_public') @common_options def get_session_data( username, password_verifier, salt, client_public, private, preset): """Print out server session data.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_public, salt, base64=True) click.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64) @client.command() @click.argument('username') @click.argument('password') @common_options @client.command() @click.argument('username') @click.argument('password') @click.argument('salt') @click.argument('server_public') @common_options def get_session_data(ctx, username, password, salt, server_public, private, preset): """Print out client session data.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) click.secho('Client session key: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64) @base.command() @click.argument('username') @click.argument('password') def get_user_data_triplet(username, password): """Print out user data triplet: username, password verifier, salt.""" context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password verifier: %s' % password_verifier) click.secho('Salt: %s' % salt) def main(): """ CLI entry point """ base(obj={})
idlesign/srptools
srptools/cli.py
get_session_data
python
def get_session_data(ctx, username, password, salt, server_public, private, preset): session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) click.secho('Client session key: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64)
Print out client session data.
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L124-L134
[ "def hex_from_b64(val):\n \"\"\"Returns hex string representation for base64 encoded value.\n\n :param str val:\n :rtype: bytes|str\n \"\"\"\n return hex_from(b64decode(val))\n", "def process(self, other_public, salt, base64=False):\n salt = self._value_decode(salt, base64)\n other_public = self._value_decode(other_public, base64)\n\n self.init_base(salt)\n self.init_common_secret(other_public)\n self.init_session_key()\n self.init_session_key_proof()\n\n key = value_encode(self._key, base64)\n key_proof = value_encode(self._key_proof, base64)\n key_proof_hash = value_encode(self._key_proof_hash, base64)\n\n return key, key_proof, key_proof_hash\n" ]
from __future__ import division from collections import OrderedDict import click from srptools import VERSION, SRPContext, SRPServerSession, SRPClientSession, hex_from_b64 from srptools.constants import * PRESETS = OrderedDict([ ('1024', (PRIME_1024, PRIME_1024_GEN)), ('1536', (PRIME_1536, PRIME_1536_GEN)), ('2048', (PRIME_2048, PRIME_2048_GEN)), ('3072', (PRIME_3072, PRIME_3072_GEN)), ('4096', (PRIME_4096, PRIME_4096_GEN)), ('6144', (PRIME_6144, PRIME_6144_GEN)), ]) @click.group() @click.version_option(version='.'.join(map(str, VERSION))) def base(): """srptools command line utility. Tools to implement Secure Remote Password (SRP) authentication. Basic scenario: > srptools get_user_data_triplet > srptools server get_private_and_public > srptools client get_private_and_public > srptools client get_session_data > srptools server get_session_data """ def common_options(func): """Commonly used command options.""" def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func @base.group() def server(): """Server session related commands.""" @base.group() def client(): """Client session related commands.""" @server.command() @click.argument('username') @click.argument('password_verifier') @common_options def get_private_and_public(username, password_verifier, private, preset): """Print out server public and private.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) click.secho('Server private: %s' % session.private_b64) click.secho('Server public: %s' % session.public_b64) @server.command() @click.argument('username') @click.argument('password_verifier') @click.argument('salt') @click.argument('client_public') @common_options def get_session_data( username, password_verifier, salt, client_public, private, preset): """Print out server session data.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_public, salt, base64=True) click.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64) @client.command() @click.argument('username') @click.argument('password') @common_options def get_private_and_public(ctx, username, password, private, preset): """Print out server public and private.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) click.secho('Client private: %s' % session.private_b64) click.secho('Client public: %s' % session.public_b64) @client.command() @click.argument('username') @click.argument('password') @click.argument('salt') @click.argument('server_public') @common_options @base.command() @click.argument('username') @click.argument('password') def get_user_data_triplet(username, password): """Print out user data triplet: username, password verifier, salt.""" context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password verifier: %s' % password_verifier) click.secho('Salt: %s' % salt) def main(): """ CLI entry point """ base(obj={})
idlesign/srptools
srptools/cli.py
get_user_data_triplet
python
def get_user_data_triplet(username, password): context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password verifier: %s' % password_verifier) click.secho('Salt: %s' % salt)
Print out user data triplet: username, password verifier, salt.
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L140-L147
[ "def get_user_data_triplet(self, base64=False):\n \"\"\"( <_user>, <_password verifier>, <salt> )\n\n :param base64:\n :rtype: tuple\n \"\"\"\n salt = self.generate_salt()\n verifier = self.get_common_password_verifier(self.get_common_password_hash(salt))\n\n verifier = value_encode(verifier, base64)\n salt = value_encode(salt, base64)\n\n return self._user, verifier, salt\n" ]
from __future__ import division from collections import OrderedDict import click from srptools import VERSION, SRPContext, SRPServerSession, SRPClientSession, hex_from_b64 from srptools.constants import * PRESETS = OrderedDict([ ('1024', (PRIME_1024, PRIME_1024_GEN)), ('1536', (PRIME_1536, PRIME_1536_GEN)), ('2048', (PRIME_2048, PRIME_2048_GEN)), ('3072', (PRIME_3072, PRIME_3072_GEN)), ('4096', (PRIME_4096, PRIME_4096_GEN)), ('6144', (PRIME_6144, PRIME_6144_GEN)), ]) @click.group() @click.version_option(version='.'.join(map(str, VERSION))) def base(): """srptools command line utility. Tools to implement Secure Remote Password (SRP) authentication. Basic scenario: > srptools get_user_data_triplet > srptools server get_private_and_public > srptools client get_private_and_public > srptools client get_session_data > srptools server get_session_data """ def common_options(func): """Commonly used command options.""" def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func @base.group() def server(): """Server session related commands.""" @base.group() def client(): """Client session related commands.""" @server.command() @click.argument('username') @click.argument('password_verifier') @common_options def get_private_and_public(username, password_verifier, private, preset): """Print out server public and private.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) click.secho('Server private: %s' % session.private_b64) click.secho('Server public: %s' % session.public_b64) @server.command() @click.argument('username') @click.argument('password_verifier') @click.argument('salt') @click.argument('client_public') @common_options def get_session_data( username, password_verifier, salt, client_public, private, preset): """Print out server session data.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_public, salt, base64=True) click.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64) @client.command() @click.argument('username') @click.argument('password') @common_options def get_private_and_public(ctx, username, password, private, preset): """Print out server public and private.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) click.secho('Client private: %s' % session.private_b64) click.secho('Client public: %s' % session.public_b64) @client.command() @click.argument('username') @click.argument('password') @click.argument('salt') @click.argument('server_public') @common_options def get_session_data(ctx, username, password, salt, server_public, private, preset): """Print out client session data.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) click.secho('Client session key: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64) @base.command() @click.argument('username') @click.argument('password') def main(): """ CLI entry point """ base(obj={})
Gjum/agarnet
agarnet/gcommer.py
gcommer_claim
python
def gcommer_claim(address=None): if not address: # get token for any world # this is only useful for testing, # because that is exactly what m.agar.io does url = 'http://at.gcommer.com/status' text = urllib.request.urlopen(url).read().decode() j = json.loads(text) for address, num in j['status'].items(): if num > 0: break # address is now one of the listed servers with tokens url = 'http://at.gcommer.com/claim?server=%s' % address text = urllib.request.urlopen(url).read().decode() j = json.loads(text) token = j['token'] return address, token
Try to get a token for this server address. `address` has to be ip:port, e.g. `'1.2.3.4:1234'` Returns tuple(address, token)
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/gcommer.py#L9-L29
null
import json import time import urllib.request from threading import Thread from .utils import find_server def gcommer_donate(address, token, *_): """ Donate a token for this server address. `address` and `token` should be the return values from find_server(). """ token = urllib.request.quote(token) url = 'http://at.gcommer.com/donate?server=%s&token=%s' % (address, token) response = urllib.request.urlopen(url).read().decode() return json.loads(response)['msg'] def gcommer_donate_threaded(interval=5, region='EU-London', mode=None): """ Run a daemon thread that requests and donates a token every `interval` seconds. """ def donate_thread(): while 1: gcommer_donate(*find_server(region, mode)) time.sleep(interval) Thread(target=donate_thread, daemon=True).start()
Gjum/agarnet
agarnet/gcommer.py
gcommer_donate
python
def gcommer_donate(address, token, *_): token = urllib.request.quote(token) url = 'http://at.gcommer.com/donate?server=%s&token=%s' % (address, token) response = urllib.request.urlopen(url).read().decode() return json.loads(response)['msg']
Donate a token for this server address. `address` and `token` should be the return values from find_server().
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/gcommer.py#L32-L40
null
import json import time import urllib.request from threading import Thread from .utils import find_server def gcommer_claim(address=None): """ Try to get a token for this server address. `address` has to be ip:port, e.g. `'1.2.3.4:1234'` Returns tuple(address, token) """ if not address: # get token for any world # this is only useful for testing, # because that is exactly what m.agar.io does url = 'http://at.gcommer.com/status' text = urllib.request.urlopen(url).read().decode() j = json.loads(text) for address, num in j['status'].items(): if num > 0: break # address is now one of the listed servers with tokens url = 'http://at.gcommer.com/claim?server=%s' % address text = urllib.request.urlopen(url).read().decode() j = json.loads(text) token = j['token'] return address, token def gcommer_donate_threaded(interval=5, region='EU-London', mode=None): """ Run a daemon thread that requests and donates a token every `interval` seconds. """ def donate_thread(): while 1: gcommer_donate(*find_server(region, mode)) time.sleep(interval) Thread(target=donate_thread, daemon=True).start()
Gjum/agarnet
agarnet/gcommer.py
gcommer_donate_threaded
python
def gcommer_donate_threaded(interval=5, region='EU-London', mode=None): def donate_thread(): while 1: gcommer_donate(*find_server(region, mode)) time.sleep(interval) Thread(target=donate_thread, daemon=True).start()
Run a daemon thread that requests and donates a token every `interval` seconds.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/gcommer.py#L43-L53
null
import json import time import urllib.request from threading import Thread from .utils import find_server def gcommer_claim(address=None): """ Try to get a token for this server address. `address` has to be ip:port, e.g. `'1.2.3.4:1234'` Returns tuple(address, token) """ if not address: # get token for any world # this is only useful for testing, # because that is exactly what m.agar.io does url = 'http://at.gcommer.com/status' text = urllib.request.urlopen(url).read().decode() j = json.loads(text) for address, num in j['status'].items(): if num > 0: break # address is now one of the listed servers with tokens url = 'http://at.gcommer.com/claim?server=%s' % address text = urllib.request.urlopen(url).read().decode() j = json.loads(text) token = j['token'] return address, token def gcommer_donate(address, token, *_): """ Donate a token for this server address. `address` and `token` should be the return values from find_server(). """ token = urllib.request.quote(token) url = 'http://at.gcommer.com/donate?server=%s&token=%s' % (address, token) response = urllib.request.urlopen(url).read().decode() return json.loads(response)['msg']
Gjum/agarnet
agarnet/client.py
Client.connect
python
def connect(self, address, token=None): if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True
Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L83-L126
[ "def send_handshake(self):\n \"\"\"\n Used by `Client.connect()`.\n\n Tells the server which protocol to use.\n Has to be sent before any other packets,\n or the server will drop the connection when receiving any other packet.\n \"\"\"\n self.send_struct('<BI', 254, 5)\n self.send_struct('<BI', 255, handshake_version)\n", "def send_token(self, token):\n \"\"\"\n Used by `Client.connect()`.\n\n After connecting to an official server and sending the\n handshake packets, the client has to send the token\n acquired through `utils.find_server()`, otherwise the server will\n drop the connection when receiving any other packet.\n \"\"\"\n self.send_struct('<B%iB' % len(token), 80, *map(ord, token))\n self.server_token = token\n", "def reset(self):\n \"\"\"\n Clears `nick` and `own_ids`, sets `center` to `world.center`,\n and then calls `cells_changed()`.\n \"\"\"\n self.own_ids.clear()\n self.nick = ''\n self.center = self.world.center\n self.cells_changed()\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.disconnect
python
def disconnect(self): self.ws.close() self.ingame = False self.subscriber.on_sock_closed()
Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L128-L136
null
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.listen
python
def listen(self): import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect()
Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L139-L153
[ "def disconnect(self):\n \"\"\"\n Disconnect from server.\n\n Closes the websocket, sets `ingame = False`, and emits on_sock_closed.\n \"\"\"\n self.ws.close()\n self.ingame = False\n self.subscriber.on_sock_closed()\n", "def on_message(self, msg=None):\n \"\"\"\n Poll the websocket for a new packet.\n\n `Client.listen()` calls this.\n\n :param msg (string(byte array)): Optional. Parse the specified message\n instead of receiving a packet from the socket.\n \"\"\"\n if msg is None:\n try:\n msg = self.ws.recv()\n except Exception as e:\n self.subscriber.on_message_error(\n 'Error while receiving packet: %s' % str(e))\n self.disconnect()\n return False\n\n if not msg:\n self.subscriber.on_message_error('Empty message received')\n return False\n\n buf = BufferStruct(msg)\n opcode = buf.pop_uint8()\n try:\n packet_name = packet_s2c[opcode]\n except KeyError:\n self.subscriber.on_message_error('Unknown packet %s' % opcode)\n return False\n\n if not self.ingame and packet_name in ingame_packets:\n self.subscriber.on_ingame()\n self.ingame = True\n\n parser = getattr(self, 'parse_%s' % packet_name)\n try:\n parser(buf)\n except BufferUnderflowError as e:\n msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0])\n self.subscriber.on_message_error(msg)\n\n if len(buf.buffer) != 0:\n msg = 'Buffer not empty after parsing \"%s\" packet' % packet_name\n self.subscriber.on_message_error(msg)\n\n return packet_name\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.on_message
python
def on_message(self, msg=None): if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name
Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L155-L200
[ "def pop_uint8(self):\n return self.pop_values('<B')[0]\n", "def disconnect(self):\n \"\"\"\n Disconnect from server.\n\n Closes the websocket, sets `ingame = False`, and emits on_sock_closed.\n \"\"\"\n self.ws.close()\n self.ingame = False\n self.subscriber.on_sock_closed()\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.send_struct
python
def send_struct(self, fmt, *data): if self.connected: self.ws.send(struct.pack(fmt, *data))
If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L363-L369
null
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.send_token
python
def send_token(self, token): self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token
Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L382-L392
[ "def send_struct(self, fmt, *data):\n \"\"\"\n If connected, formats the data to a struct and sends it to the server.\n Used internally by all other `send_*()` methods.\n \"\"\"\n if self.connected:\n self.ws.send(struct.pack(fmt, *data))\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.send_facebook
python
def send_facebook(self, token): self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token
Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L394-L404
[ "def send_struct(self, fmt, *data):\n \"\"\"\n If connected, formats the data to a struct and sends it to the server.\n Used internally by all other `send_*()` methods.\n \"\"\"\n if self.connected:\n self.ws.send(struct.pack(fmt, *data))\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.send_respawn
python
def send_respawn(self): nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick))
Respawns the player.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L406-L411
[ "def send_struct(self, fmt, *data):\n \"\"\"\n If connected, formats the data to a struct and sends it to the server.\n Used internally by all other `send_*()` methods.\n \"\"\"\n if self.connected:\n self.ws.send(struct.pack(fmt, *data))\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.send_target
python
def send_target(self, x, y, cid=0): self.send_struct('<BiiI', 16, int(x), int(y), cid)
Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L413-L427
[ "def send_struct(self, fmt, *data):\n \"\"\"\n If connected, formats the data to a struct and sends it to the server.\n Used internally by all other `send_*()` methods.\n \"\"\"\n if self.connected:\n self.ws.send(struct.pack(fmt, *data))\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21) def send_explode(self): """ In earlier versions of the game, sending this caused your cells to split into lots of small cells and die. """ self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
Gjum/agarnet
agarnet/client.py
Client.send_explode
python
def send_explode(self): self.send_struct('<B', 20) self.player.own_ids.clear() self.player.cells_changed() self.ingame = False self.subscriber.on_death()
In earlier versions of the game, sending this caused your cells to split into lots of small cells and die.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/client.py#L461-L470
[ "def send_struct(self, fmt, *data):\n \"\"\"\n If connected, formats the data to a struct and sends it to the server.\n Used internally by all other `send_*()` methods.\n \"\"\"\n if self.connected:\n self.ws.send(struct.pack(fmt, *data))\n" ]
class Client(object): """Talks to a server and calls handlers on events.""" def __init__(self, subscriber): """ :param subscriber: class instance that implements any on_*() methods """ self.subscriber = subscriber # Gets updated with the new data when the server sends a packet. self.player = Player() # The websocket instance used to connect to the server. self.ws = websocket.WebSocket() # The most recent address used to connect to the server. self.address = '' # The most recent token used to connect to the server. self.server_token = '' # The most recent Facebook token sent to a server. self.facebook_token = '' # `False` after connection, gets set to `True` when # receiving a packet listed in `ingame_packets`. self.ingame = False @property def world(self): return self.player.world @world.setter def world(self, world): self.player.world = world @property def connected(self): return self.ws.connected def connect(self, address, token=None): """ Connect the underlying websocket to the address, send a handshake and optionally a token packet. Returns `True` if connected, `False` if the connection failed. :param address: string, `IP:PORT` :param token: unique token, required by official servers, acquired through utils.find_server() :return: True if connected, False if not """ if self.connected: self.subscriber.on_connect_error( 'Already connected to "%s"' % self.address) return False self.address = address self.server_token = token self.ingame = False self.ws.settimeout(1) self.ws.connect('ws://%s' % self.address, origin='http://agar.io') if not self.connected: self.subscriber.on_connect_error( 'Failed to connect to "%s"' % self.address) return False self.subscriber.on_sock_open() # allow handshake canceling if not self.connected: self.subscriber.on_connect_error( 'Disconnected before sending handshake') return False self.send_handshake() if self.server_token: self.send_token(self.server_token) old_nick = self.player.nick self.player.reset() self.world.reset() self.player.nick = old_nick return True def disconnect(self): """ Disconnect from server. Closes the websocket, sets `ingame = False`, and emits on_sock_closed. """ self.ws.close() self.ingame = False self.subscriber.on_sock_closed() # keep player/world data def listen(self): """ Set up a quick connection. Returns on disconnect. After calling `connect()`, this waits for messages from the server using `select`, and notifies the subscriber of any events. """ import select while self.connected: r, w, e = select.select((self.ws.sock, ), (), ()) if r: self.on_message() elif e: self.subscriber.on_sock_error(e) self.disconnect() def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: msg = self.ws.recv() except Exception as e: self.subscriber.on_message_error( 'Error while receiving packet: %s' % str(e)) self.disconnect() return False if not msg: self.subscriber.on_message_error('Empty message received') return False buf = BufferStruct(msg) opcode = buf.pop_uint8() try: packet_name = packet_s2c[opcode] except KeyError: self.subscriber.on_message_error('Unknown packet %s' % opcode) return False if not self.ingame and packet_name in ingame_packets: self.subscriber.on_ingame() self.ingame = True parser = getattr(self, 'parse_%s' % packet_name) try: parser(buf) except BufferUnderflowError as e: msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0]) self.subscriber.on_message_error(msg) if len(buf.buffer) != 0: msg = 'Buffer not empty after parsing "%s" packet' % packet_name self.subscriber.on_message_error(msg) return packet_name def parse_world_update(self, buf): self.subscriber.on_world_update_pre() self.parse_cell_eating(buf) self.parse_cell_updates(buf) self.parse_cell_deletions(buf) if self.player.is_alive: self.player.cells_changed() self.subscriber.on_world_update_post() def parse_cell_eating(self, buf): for i in range(buf.pop_uint16()): # ca eats cb ca = buf.pop_uint32() cb = buf.pop_uint32() self.subscriber.on_cell_eaten(eater_id=ca, eaten_id=cb) if cb in self.player.own_ids: # we got eaten if len(self.player.own_ids) <= 1: self.subscriber.on_death() # do not clear all cells yet, they still get updated self.player.own_ids.remove(cb) if cb in self.player.world.cells: self.subscriber.on_cell_removed(cid=cb) del self.player.world.cells[cb] def parse_cell_updates(self, buf): # create/update cells while 1: cid = buf.pop_uint32() if cid == 0: break cx = buf.pop_int32() cy = buf.pop_int32() csize = buf.pop_int16() color = (buf.pop_uint8(), buf.pop_uint8(), buf.pop_uint8()) bitmask = buf.pop_uint8() is_virus = bool(bitmask & 1) is_agitated = bool(bitmask & 16) if bitmask & 2: # skip padding for i in range(buf.pop_uint32()): buf.pop_uint8() if bitmask & 4: # skin URL skin_url = buf.pop_str8() else: # no skin URL given skin_url = '' cname = buf.pop_str16() self.subscriber.on_cell_info( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if cid not in self.player.world.cells: self.world.create_cell(cid) self.player.world.cells[cid].update( cid=cid, x=cx, y=cy, size=csize, name=cname, color=color, is_virus=is_virus, is_agitated=is_agitated) if skin_url: # TODO Cell.update() and on_cell_info got too bulky self.subscriber.on_cell_skin(skin_url=skin_url) def parse_cell_deletions(self, buf): cells = self.player.world.cells # also keep these non-updated cells for i in range(buf.pop_uint32()): cid = buf.pop_uint32() if cid in cells: self.subscriber.on_cell_removed(cid=cid) del cells[cid] if cid in self.player.own_ids: # own cells joined self.player.own_ids.remove(cid) def parse_leaderboard_names(self, buf): # sent every 500ms # not in "teams" mode n = buf.pop_uint32() leaderboard_names = [] for i in range(n): l_id = buf.pop_uint32() l_name = buf.pop_str16() leaderboard_names.append((l_id, l_name)) self.subscriber.on_leaderboard_names(leaderboard=leaderboard_names) self.player.world.leaderboard_names = leaderboard_names def parse_leaderboard_groups(self, buf): # sent every 500ms # only in "teams" mode n = buf.pop_uint32() leaderboard_groups = [] for i in range(n): angle = buf.pop_float32() leaderboard_groups.append(angle) self.subscriber.on_leaderboard_groups(angles=leaderboard_groups) self.player.world.leaderboard_groups = leaderboard_groups def parse_own_id(self, buf): # new cell ID, respawned or split cid = buf.pop_uint32() if not self.player.is_alive: # respawned self.player.own_ids.clear() self.subscriber.on_respawn() # server sends empty name, assumes we set it here if cid not in self.world.cells: self.world.create_cell(cid) # self.world.cells[cid].name = self.player.nick self.player.own_ids.add(cid) self.player.cells_changed() self.subscriber.on_own_id(cid=cid) def parse_world_rect(self, buf): # world size left = buf.pop_float64() top = buf.pop_float64() right = buf.pop_float64() bottom = buf.pop_float64() self.subscriber.on_world_rect( left=left, top=top, right=right, bottom=bottom) self.world.top_left = Vec(top, left) self.world.bottom_right = Vec(bottom, right) if buf.buffer: number = buf.pop_uint32() text = buf.pop_str16() self.subscriber.on_server_version(number=number, text=text) def parse_spectate_update(self, buf): # only in spectate mode x = buf.pop_float32() y = buf.pop_float32() scale = buf.pop_float32() self.player.center.set(x, y) self.player.scale = scale self.subscriber.on_spectate_update( pos=self.player.center, scale=scale) def parse_experience_info(self, buf): level = buf.pop_uint32() current_xp = buf.pop_uint32() next_xp = buf.pop_uint32() self.subscriber.on_experience_info( level=level, current_xp=current_xp, next_xp=next_xp) def parse_clear_cells(self, buf): # TODO clear cells packet is untested self.subscriber.on_clear_cells() self.world.cells.clear() self.player.own_ids.clear() self.player.cells_changed() def parse_debug_line(self, buf): # TODO debug line packet is untested x = buf.pop_int16() y = buf.pop_int16() self.subscriber.on_debug_line(x=x, y=y) # format reminder # b int8 # h int16 # i int32 # f float32 # d float64 def send_struct(self, fmt, *data): """ If connected, formats the data to a struct and sends it to the server. Used internally by all other `send_*()` methods. """ if self.connected: self.ws.send(struct.pack(fmt, *data)) def send_handshake(self): """ Used by `Client.connect()`. Tells the server which protocol to use. Has to be sent before any other packets, or the server will drop the connection when receiving any other packet. """ self.send_struct('<BI', 254, 5) self.send_struct('<BI', 255, handshake_version) def send_token(self, token): """ Used by `Client.connect()`. After connecting to an official server and sending the handshake packets, the client has to send the token acquired through `utils.find_server()`, otherwise the server will drop the connection when receiving any other packet. """ self.send_struct('<B%iB' % len(token), 80, *map(ord, token)) self.server_token = token def send_facebook(self, token): """ Tells the server which Facebook account this client uses. After sending, the server takes some time to get the data from Facebook. Seems to be broken in recent versions of the game. """ self.send_struct('<B%iB' % len(token), 81, *map(ord, token)) self.facebook_token = token def send_respawn(self): """ Respawns the player. """ nick = self.player.nick self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) def send_target(self, x, y, cid=0): """ Sets the target position of all cells. `x` and `y` are world coordinates. They can exceed the world border. For continuous movement, send a new target position before the old one is reached. In earlier versions of the game, it was possible to control each cell individually by specifying the cell's `cid`. Same as moving your mouse in the original client. """ self.send_struct('<BiiI', 16, int(x), int(y), cid) def send_spectate(self): """ Puts the player into spectate mode. The server then starts sending `spectate_update` packets containing the center and size of the spectated area. """ self.send_struct('<B', 1) def send_spectate_toggle(self): """ Toggles the spectate mode between following the largest player and moving around freely. """ self.send_struct('<B', 18) def send_split(self): """ Splits all controlled cells, while not exceeding 16 cells. Same as pressing `Space` in the original client. """ self.send_struct('<B', 17) def send_shoot(self): """ Ejects a pellet from all controlled cells. Same as pressing `W` in the original client. """ self.send_struct('<B', 21)
Gjum/agarnet
agarnet/world.py
Cell.same_player
python
def same_player(self, other): return self.name == other.name \ and self.color == other.color
Compares name and color. Returns True if both are owned by the same player.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L28-L34
null
class Cell(object): def __init__(self, *args, **kwargs): self.pos = Vec() self.update(*args, **kwargs) def update(self, cid=-1, x=0, y=0, size=0, name='', color=(1, 0, 1), is_virus=False, is_agitated=False): self.cid = cid self.pos.set(x, y) self.size = size self.mass = size ** 2 / 100.0 self.name = getattr(self, 'name', name) or name self.color = tuple(map(lambda rgb: rgb / 255.0, color)) self.is_virus = is_virus self.is_agitated = is_agitated @property def is_food(self): return self.size < 20 and not self.name @property def is_ejected_mass(self): return self.size in (37, 38) and not self.name def __lt__(self, other): if self.mass != other.mass: return self.mass < other.mass return self.cid < other.cid
Gjum/agarnet
agarnet/world.py
World.reset
python
def reset(self): self.cells.clear() self.leaderboard_names.clear() self.leaderboard_groups.clear() self.top_left.set(0, 0) self.bottom_right.set(0, 0)
Clears the `cells` and leaderboards, and sets all corners to `0,0`.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L53-L61
[ "def set(self, x, y):\n self.x = x\n self.y = y\n return self\n" ]
class World(object): cell_class = Cell def __init__(self): self.cells = {} self.leaderboard_names = [] self.leaderboard_groups = [] self.top_left = Vec(0, 0) self.bottom_right = Vec(0, 0) self.reset() def create_cell(self, cid): """ Creates a new cell in the world. Override to use a custom cell class. """ self.cells[cid] = self.cell_class() @property def center(self): return (self.top_left + self.bottom_right) / 2 @property def size(self): return self.top_left.abs() + self.bottom_right.abs() def __eq__(self, other): """Compares two worlds by comparing their leaderboards.""" for ls, lo in zip(self.leaderboard_names, other.leaderboard_names): if ls != lo: return False for ls, lo in zip(self.leaderboard_groups, other.leaderboard_groups): if ls != lo: return False if self.top_left != other.top_left: return False if self.bottom_right != other.bottom_right: return False return True
Gjum/agarnet
agarnet/world.py
Player.reset
python
def reset(self): self.own_ids.clear() self.nick = '' self.center = self.world.center self.cells_changed()
Clears `nick` and `own_ids`, sets `center` to `world.center`, and then calls `cells_changed()`.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L115-L123
[ "def cells_changed(self):\n \"\"\"\n Calculates `total_size`, `total_mass`, `scale`, and `center`.\n\n Has to be called when the controlled cells (`own_ids`) change.\n \"\"\"\n self.total_size = sum(cell.size for cell in self.own_cells)\n self.total_mass = sum(cell.mass for cell in self.own_cells)\n self.scale = pow(min(1.0, 64.0 / self.total_size), 0.4) \\\n if self.total_size > 0 else 1.0\n\n if self.own_ids:\n left = min(cell.pos.x for cell in self.own_cells)\n right = max(cell.pos.x for cell in self.own_cells)\n top = min(cell.pos.y for cell in self.own_cells)\n bottom = max(cell.pos.y for cell in self.own_cells)\n self.center = Vec(left + right, top + bottom) / 2\n" ]
class Player(object): def __init__(self): # The world that the player's cells are in. self.world = World() # All controlled cell IDs. self.own_ids = set() # The center of all controlled cells. self.center = self.world.center # Combined size of all controlled cells. self.total_size = 0 # Combined mass of all controlled cells. self.total_mass = 0 self.nick = '' self.scale = 1.0 self.reset() def cells_changed(self): """ Calculates `total_size`, `total_mass`, `scale`, and `center`. Has to be called when the controlled cells (`own_ids`) change. """ self.total_size = sum(cell.size for cell in self.own_cells) self.total_mass = sum(cell.mass for cell in self.own_cells) self.scale = pow(min(1.0, 64.0 / self.total_size), 0.4) \ if self.total_size > 0 else 1.0 if self.own_ids: left = min(cell.pos.x for cell in self.own_cells) right = max(cell.pos.x for cell in self.own_cells) top = min(cell.pos.y for cell in self.own_cells) bottom = max(cell.pos.y for cell in self.own_cells) self.center = Vec(left + right, top + bottom) / 2 # else: keep old center @property def own_cells(self): cells = self.world.cells return (cells[cid] for cid in self.own_ids) @property def is_alive(self): return bool(self.own_ids) @property def is_spectating(self): return not self.is_alive @property def visible_area(self): """ Calculated like in the official client. Returns (top_left, bottom_right). """ # looks like zeach has a nice big screen half_viewport = Vec(1920, 1080) / 2 / self.scale top_left = self.world.center - half_viewport bottom_right = self.world.center + half_viewport return top_left, bottom_right
Gjum/agarnet
agarnet/world.py
Player.cells_changed
python
def cells_changed(self): self.total_size = sum(cell.size for cell in self.own_cells) self.total_mass = sum(cell.mass for cell in self.own_cells) self.scale = pow(min(1.0, 64.0 / self.total_size), 0.4) \ if self.total_size > 0 else 1.0 if self.own_ids: left = min(cell.pos.x for cell in self.own_cells) right = max(cell.pos.x for cell in self.own_cells) top = min(cell.pos.y for cell in self.own_cells) bottom = max(cell.pos.y for cell in self.own_cells) self.center = Vec(left + right, top + bottom) / 2
Calculates `total_size`, `total_mass`, `scale`, and `center`. Has to be called when the controlled cells (`own_ids`) change.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L125-L141
null
class Player(object): def __init__(self): # The world that the player's cells are in. self.world = World() # All controlled cell IDs. self.own_ids = set() # The center of all controlled cells. self.center = self.world.center # Combined size of all controlled cells. self.total_size = 0 # Combined mass of all controlled cells. self.total_mass = 0 self.nick = '' self.scale = 1.0 self.reset() def reset(self): """ Clears `nick` and `own_ids`, sets `center` to `world.center`, and then calls `cells_changed()`. """ self.own_ids.clear() self.nick = '' self.center = self.world.center self.cells_changed() # else: keep old center @property def own_cells(self): cells = self.world.cells return (cells[cid] for cid in self.own_ids) @property def is_alive(self): return bool(self.own_ids) @property def is_spectating(self): return not self.is_alive @property def visible_area(self): """ Calculated like in the official client. Returns (top_left, bottom_right). """ # looks like zeach has a nice big screen half_viewport = Vec(1920, 1080) / 2 / self.scale top_left = self.world.center - half_viewport bottom_right = self.world.center + half_viewport return top_left, bottom_right
Gjum/agarnet
agarnet/world.py
Player.visible_area
python
def visible_area(self): # looks like zeach has a nice big screen half_viewport = Vec(1920, 1080) / 2 / self.scale top_left = self.world.center - half_viewport bottom_right = self.world.center + half_viewport return top_left, bottom_right
Calculated like in the official client. Returns (top_left, bottom_right).
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L159-L168
null
class Player(object): def __init__(self): # The world that the player's cells are in. self.world = World() # All controlled cell IDs. self.own_ids = set() # The center of all controlled cells. self.center = self.world.center # Combined size of all controlled cells. self.total_size = 0 # Combined mass of all controlled cells. self.total_mass = 0 self.nick = '' self.scale = 1.0 self.reset() def reset(self): """ Clears `nick` and `own_ids`, sets `center` to `world.center`, and then calls `cells_changed()`. """ self.own_ids.clear() self.nick = '' self.center = self.world.center self.cells_changed() def cells_changed(self): """ Calculates `total_size`, `total_mass`, `scale`, and `center`. Has to be called when the controlled cells (`own_ids`) change. """ self.total_size = sum(cell.size for cell in self.own_cells) self.total_mass = sum(cell.mass for cell in self.own_cells) self.scale = pow(min(1.0, 64.0 / self.total_size), 0.4) \ if self.total_size > 0 else 1.0 if self.own_ids: left = min(cell.pos.x for cell in self.own_cells) right = max(cell.pos.x for cell in self.own_cells) top = min(cell.pos.y for cell in self.own_cells) bottom = max(cell.pos.y for cell in self.own_cells) self.center = Vec(left + right, top + bottom) / 2 # else: keep old center @property def own_cells(self): cells = self.world.cells return (cells[cid] for cid in self.own_ids) @property def is_alive(self): return bool(self.own_ids) @property def is_spectating(self): return not self.is_alive @property
Gjum/agarnet
agarnet/utils.py
find_server
python
def find_server(region='EU-London', mode=None): if mode: region = '%s:%s' % (region, mode) opener = urllib.request.build_opener() opener.addheaders = default_headers data = '%s\n%s' % (region, handshake_version) return opener.open('http://m.agar.io/', data=data.encode()) \ .read().decode().split('\n')[0:2]
Returns `(address, token)`, both strings. `mode` is the game mode of the requested server. It can be `'party'`, `'teams'`, `'experimental'`, or `None` for "Free for all". The returned `address` is in `'IP:port'` format. Makes a request to http://m.agar.io to get address and token.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/utils.py#L20-L37
null
import urllib.error import urllib.request from .client import handshake_version # List of names that always have a skin on the official client. special_names = 'poland;usa;china;russia;canada;australia;spain;brazil;germany;ukraine;france;sweden;chaplin;north korea;south korea;japan;united kingdom;earth;greece;latvia;lithuania;estonia;finland;norway;cia;maldivas;austria;nigeria;reddit;yaranaika;confederate;9gag;indiana;4chan;italy;bulgaria;tumblr;2ch.hk;hong kong;portugal;jamaica;german empire;mexico;sanik;switzerland;croatia;chile;indonesia;bangladesh;thailand;iran;iraq;peru;moon;botswana;bosnia;netherlands;european union;taiwan;pakistan;hungary;satanist;qing dynasty;matriarchy;patriarchy;feminism;ireland;texas;facepunch;prodota;cambodia;steam;piccolo;ea;india;kc;denmark;quebec;ayy lmao;sealand;bait;tsarist russia;origin;vinesauce;stalin;belgium;luxembourg;stussy;prussia;8ch;argentina;scotland;sir;romania;belarus;wojak;doge;nasa;byzantium;imperial japan;french kingdom;somalia;turkey;mars;pokerface;8;irs;receita federal;facebook;putin;merkel;tsipras;obama;kim jong-un;dilma;hollande;berlusconi;cameron;clinton;hillary;venezuela;blatter;chavez;cuba;fidel;palin;queen;boris;bush;trump;underwood' \ .split(';') # Used to make the requests to `m.agar.io`. Sets the # `User-Agent` to Firefox and the `Origin` and `Referer` to `http://agar.io`. default_headers = [ ('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'), ('Origin', 'http://agar.io'), ('Referer', 'http://agar.io'), ] def get_party_address(party_token): """ Returns the address (`'IP:port'` string) of the party server. To generate a `party_token`: ``` from agarnet.utils import find_server _, token = find_server(mode='party') ``` Makes a request to http://m.agar.io/getToken to get the address. """ opener = urllib.request.build_opener() opener.addheaders = default_headers try: data = party_token.encode() return opener.open('http://m.agar.io/getToken', data=data) \ .read().decode().split('\n')[0] except urllib.error.HTTPError: raise ValueError('Invalid token "%s" (maybe timed out,' ' try creating a new one)' % party_token)
Gjum/agarnet
agarnet/utils.py
get_party_address
python
def get_party_address(party_token): opener = urllib.request.build_opener() opener.addheaders = default_headers try: data = party_token.encode() return opener.open('http://m.agar.io/getToken', data=data) \ .read().decode().split('\n')[0] except urllib.error.HTTPError: raise ValueError('Invalid token "%s" (maybe timed out,' ' try creating a new one)' % party_token)
Returns the address (`'IP:port'` string) of the party server. To generate a `party_token`: ``` from agarnet.utils import find_server _, token = find_server(mode='party') ``` Makes a request to http://m.agar.io/getToken to get the address.
train
https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/utils.py#L40-L60
null
import urllib.error import urllib.request from .client import handshake_version # List of names that always have a skin on the official client. special_names = 'poland;usa;china;russia;canada;australia;spain;brazil;germany;ukraine;france;sweden;chaplin;north korea;south korea;japan;united kingdom;earth;greece;latvia;lithuania;estonia;finland;norway;cia;maldivas;austria;nigeria;reddit;yaranaika;confederate;9gag;indiana;4chan;italy;bulgaria;tumblr;2ch.hk;hong kong;portugal;jamaica;german empire;mexico;sanik;switzerland;croatia;chile;indonesia;bangladesh;thailand;iran;iraq;peru;moon;botswana;bosnia;netherlands;european union;taiwan;pakistan;hungary;satanist;qing dynasty;matriarchy;patriarchy;feminism;ireland;texas;facepunch;prodota;cambodia;steam;piccolo;ea;india;kc;denmark;quebec;ayy lmao;sealand;bait;tsarist russia;origin;vinesauce;stalin;belgium;luxembourg;stussy;prussia;8ch;argentina;scotland;sir;romania;belarus;wojak;doge;nasa;byzantium;imperial japan;french kingdom;somalia;turkey;mars;pokerface;8;irs;receita federal;facebook;putin;merkel;tsipras;obama;kim jong-un;dilma;hollande;berlusconi;cameron;clinton;hillary;venezuela;blatter;chavez;cuba;fidel;palin;queen;boris;bush;trump;underwood' \ .split(';') # Used to make the requests to `m.agar.io`. Sets the # `User-Agent` to Firefox and the `Origin` and `Referer` to `http://agar.io`. default_headers = [ ('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'), ('Origin', 'http://agar.io'), ('Referer', 'http://agar.io'), ] def find_server(region='EU-London', mode=None): """ Returns `(address, token)`, both strings. `mode` is the game mode of the requested server. It can be `'party'`, `'teams'`, `'experimental'`, or `None` for "Free for all". The returned `address` is in `'IP:port'` format. Makes a request to http://m.agar.io to get address and token. """ if mode: region = '%s:%s' % (region, mode) opener = urllib.request.build_opener() opener.addheaders = default_headers data = '%s\n%s' % (region, handshake_version) return opener.open('http://m.agar.io/', data=data.encode()) \ .read().decode().split('\n')[0:2]
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
synchronizeLayout
python
def synchronizeLayout(primary, secondary, surface_size): primary.configure_bound(surface_size) secondary.configure_bound(surface_size) # Check for key size. if (primary.key_size < secondary.key_size): logging.warning('Normalizing key size from secondary to primary') secondary.key_size = primary.key_size elif (primary.key_size > secondary.key_size): logging.warning('Normalizing key size from primary to secondary') primary.key_size = secondary.key_size if (primary.size[1] > secondary.size[1]): logging.warning('Normalizing layout size from secondary to primary') secondary.set_size(primary.size, surface_size) elif (primary.size[1] < secondary.size[1]): logging.warning('Normalizing layout size from primary to secondary') primary.set_size(secondary.size, surface_size)
Synchronizes given layouts by normalizing height by using max height of given layouts to avoid transistion dirty effects. :param primary: Primary layout used. :param secondary: Secondary layout used. :param surface_size: Target surface size on which layout will be displayed.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L526-L548
null
#!/usr/bin/python # coding: utf-8 """Visual keyboard for Pygame engine. Aims to be easy to use as highly customizable as well. ``VKeyboard`` only require a pygame surface to be displayed on and a text consumer function, as in the following example : ```python from pygame_vkeyboard import * # Initializes your window object or surface your want # vkeyboard to be displayed on top of. surface = ... def consume(text): print(repr('Current text : %s' % text)) # Initializes and activates vkeyboard layout = VKeyboardLayout(VKeyboardLayout.AZERTY) keyboard = VKeyboard(window, consumer, layout) keyboard.enable() ``` """ import logging import pygame from os.path import join, dirname from pygame.locals import * pygame.font.init() # Configure logger. logging.basicConfig() logger = logging.getLogger(__name__) class VKeyboardRenderer(object): """A VKeyboardRenderer is in charge of keyboard rendering. It handles keyboard rendering properties such as color or padding, and provides two rendering methods : one for the keyboard background and another one the the key rendering. .. note:: A DEFAULT style instance is available as class attribute. """ def __init__(self, font, keyboard_background_color, key_background_color, text_color, special_key_background_color=None): """VKeyboardStyle default constructor. :param font: Used font for rendering key. :param keyboard_background_color: Background color use for the keyboard. :param key_background_color: Tuple of background color for key (one value per state). :param text_color: Tuple of key text color (one value per state). :param special_key_background_color: Background color for special key if required. """ self.font = font self.keyboard_background_color = keyboard_background_color self.key_background_color = key_background_color self.special_key_background_color = special_key_background_color self.text_color = text_color def draw_background(self, surface, position, size): """Default drawing method for background. Background is drawn as a simple rectangle filled using this style background color attribute. :param surface: Surface background should be drawn in. :param position: Surface relative position the keyboard should be drawn at. :param size: Expected size of the drawn keyboard. """ pygame.draw.rect(surface, self.keyboard_background_color, position + size) def draw_key(self, surface, key): """Default drawing method for key. Draw the key accordingly to it type. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ if isinstance(key, VSpaceKey): self.draw_space_key(surface, key) elif isinstance(key, VBackKey): self.draw_back_key(surface, key) elif isinstance(key, VUppercaseKey): self.draw_uppercase_key(surface, key) elif isinstance(key, VSpecialCharKey): self.draw_special_char_key(surface, key) else: self.draw_character_key(surface, key) def draw_character_key(self, surface, key, special=False): """Default drawing method for key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. :param special: BOolean flag that indicates if the drawn key should use special background color if available. """ background_color = self.key_background_color if special and self.special_key_background_color is not None: background_color = self.special_key_background_color pygame.draw.rect(surface, background_color[key.state], key.position + key.size) size = self.font.size(key.value) x = key.position[0] + ((key.size[0] - size[0]) / 2) y = key.position[1] + ((key.size[1] - size[1]) / 2) surface.blit(self.font.render(key.value, 1, self.text_color[key.state], None), (x, y)) def draw_space_key(self, surface, key): """Default drawing method space key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, False) def draw_back_key(self, surface, key): """Default drawing method for back key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, True) def draw_uppercase_key(self, surface, key): """Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'\u21e7' if key.is_activated(): key.value = u'\u21ea' self.draw_character_key(surface, key, True) def draw_special_char_key(self, surface, key): """Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'#' if key.is_activated(): key.value = u'Ab' self.draw_character_key(surface, key, True) """ Default style implementation. """ VKeyboardRenderer.DEFAULT = VKeyboardRenderer( pygame.font.Font(join(dirname(__file__), 'DejaVuSans.ttf'), 25), (255, 255, 255), ((255, 255, 255), (0, 0, 0)), ((0, 0, 0), (255, 255, 255)), ((180, 180, 180), (0, 0, 0)), ) class VKey(object): """Simple key holder class. Holds key information (its value), as it's state, 1 for pressed, 0 for released. Also contains it size / position properties. """ def __init__(self, value): """Default key constructor. :param value: Value of this key which also is the label displayed to the screen. """ self.state = 0 self.value = value self.position = (0, 0) self.size = (0, 0) def set_size(self, size): """Sets the size of this key. :param size: Size of this key. """ self.size = (size, size) def is_touched(self, position): """Hit detection method. Indicates if this key has been hit by a touch / click event at the given position. :param position: Event position. :returns: True is the given position collide this key, False otherwise. """ return position[0] >= self.position[0] and position[0] <= self.position[0]+ self.size[0] def update_buffer(self, buffer): """Text update method. Aims to be called internally when a key collision has been detected. Updates and returns the given buffer using this key value. :param buffer: Buffer to be updated. :returns: Updated buffer value. """ return buffer + self.value class VSpaceKey(VKey): """ Custom key for spacebar. """ def __init__(self, length): """Default constructor. :param length: Key length. """ VKey.__init__(self, 'Space') self.length = length def set_size(self, size): """Sets the size of this key. :param size: Size of this key. """ self.size = (size * self.length, size) def update_buffer(self, buffer): """Text update method. Adds space to the given buffer. :param buffer: Buffer to be updated. :returns: Updated buffer value. """ return buffer + ' ' class VBackKey(VKey): """ Custom key for back. """ def __init__(self): """ Default constructor. """ VKey.__init__(self, u'\u21a9') def update_buffer(self, buffer): """Text update method. Removes last character. :param buffer: Buffer to be updated. :returns: Updated buffer value. """ return buffer[:-1] class VActionKey(VKey): """A VActionKey is a key that trigger and action rather than updating the buffer when pressed. """ def __init__(self, action, state_holder): """Default constructor. :param action: Delegate action called when this key is pressed. :param state_holder: Holder for this key state (activated or not). """ VKey.__init__(self, '') self.action = action self.state_holder = state_holder def update_buffer(self, buffer): """Do not update text but trigger the delegate action. :param buffer: Not used, just to match parent interface. :returns: Buffer provided as parameter. """ self.action() return buffer class VUppercaseKey(VActionKey): """ Action key for the uppercase switch. """ def __init__(self, keyboard): """ Default constructor. :param keyboard: Keyboard to trigger on_uppercase() when pressed. """ VActionKey.__init__(self, lambda: keyboard.on_uppercase(), keyboard) def is_activated(self): """Indicates if this key is activated. :returns: True if activated, False otherwise: """ return self.state_holder.uppercase class VSpecialCharKey(VActionKey): """ Action key for the special char switch. """ def __init__(self, keyboard): """ Default constructor. :param keyboard: Keyboard to trigger on_special_char() when pressed. """ VActionKey.__init__(self, lambda: keyboard.on_special_char(), keyboard) def is_activated(self): """Indicates if this key is activated. :returns: True if activated, False otherwise: """ return self.state_holder.special_char class VKeyRow(object): """A VKeyRow defines a keyboard row which is composed of a list of VKey. This class aims to be created internally after parsing a keyboard layout model. It is used to optimize collision detection, by first checking row collision, then internal row key detection. """ def __init__(self): """ Default row constructor. """ self.keys = [] self.y = -1 self.height = 0 self.space = None def add_key(self, key, first=False): """Adds the given key to this row. :param key: Key to be added to this row. :param first: BOolean flag that indicates if key is added at the beginning or at the end. """ if first: self.keys = [key] + self.keys else: self.keys.append(key) if isinstance(key, VSpaceKey): self.space = key def set_size(self, position, size, padding): """Row size setter. The size correspond to the row height, since the row width is constraint to the surface width the associated keyboard belongs. Once size is settled, the size for each child keys is associated. :param position: Position of this row. :param size: Size of the row (height) :param padding: Padding between key. """ self.height = size self.position = position x = position[0] for key in self.keys: key.set_size(size) key.position = (x, position[1]) x += padding + key.size[0] def __contains__(self, position): """Indicates if the given position collide this row. :param position: Position to check againt this row. :returns: True if the given position collide this row, False otherwise. """ return position[1] >= self.position[1] and position[1] <= self.position[1] + self.height def __len__(self): """len() operator overload. :returns: Number of keys thi row contains. """ return len(self.keys) class VKeyboardLayout(object): """Keyboard layout class. A keyboard layout is built using layout model which consists in an list of supported character. Such list item as simple string containing characters assigned to a row. An erasing key is inserted automatically to the first row. If allowUpperCase flag is True, then an upper case key will be inserted at the beginning of the second row. If allowSpecialChars flag is True, then an special characters / number key will be inserted at the beginning of the third row. Pressing this key will switch the associated keyboard current layout. """ """ Azerty layout. """ AZERTY = ['1234567890', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'] """ Number only layout. """ NUMBER = ['123', '456', '789', '0'] """ """ SPECIAL = [u'&é"\'(§è!çà)', u'°_-^$¨*ù`%£', u',;:=?.@+<>#', u'[]{}/\\|'] # TODO : Insert special characters layout which include number. def __init__(self, model, key_size=None, padding=5, allow_uppercase=True, allow_special_chars=True, allow_space=True): """Default constructor. Initializes layout rows. :param model: Layout model to use. :param key_size Size of the key, if not specified will be computed dynamically. :param padding: Padding between key (work horizontally as vertically). :param allowUpperCase: Boolean flag that indicates usage of upper case switching key. :param allowSpecialChars: Boolean flag that indicates usage of special char switching key. :param allowSpace: Boolean flag that indicates usage of space bar. """ self.rows = [] self.key_size = key_size self.padding = padding self.allow_space = allow_space self.allow_uppercase = allow_uppercase self.allow_special_chars = allow_special_chars for model_row in model: row = VKeyRow() for value in model_row: row.add_key(VKey(value)) self.rows.append(row) self.max_length = len(max(self.rows, key=len)) if self.max_length == 0: raise ValueError('Empty layout model provided') def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard)) while len(special_keys) > 0: first = False while len(special_keys) > 0 and len(current_row) < max_length: current_row.add_key(special_keys.pop(0), first=first) first = not first if i > 0: i -= 1 current_row = self.rows[i] else: break if self.allow_space: space_length = len(current_row) - len(special_keys) special_row.add_key(VSpaceKey(space_length)) first = True # Adding left to the special bar. while len(special_keys) > 0: special_row.add_key(special_keys.pop(0), first=first) first = not first if len(special_row) > 0: self.rows.append(special_row) def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size) def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surface_size[0] - width) / 2 if row.space is not None: x -= ((row.space.length - 1) * self.key_size) / 2 row.set_size((x, y), self.key_size, self.padding) y += self.padding + self.key_size def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0 def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower() def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None class VKeyboard(object): """Virtual Keyboard class. A virtual keyboard consists in a VKeyboardLayout that acts as the keyboard model and a VKeyboardRenderer which is in charge of drawing keyboard component to screen. """ def __init__(self, surface, text_consumer, layout, special_char_layout=VKeyboardLayout(VKeyboardLayout.SPECIAL), renderer=VKeyboardRenderer.DEFAULT): """Default constructor. :param surface: Surface this keyboard will be displayed at. :param text_consumer: Consumer that process text for each update. :param layout: Layout this keyboard will use. :param special_char_layout: Alternative layout to use, using VKeyboardLayout.SPECIAL if not specified. :param renderer: Keyboard renderer instance, using VKeyboardStyle.DEFAULT if not specified. """ self.surface = surface self.text_consumer = text_consumer self.renderer = renderer self.buffer = u'' self.state = 0 self.last_pressed = None self.uppercase = False self.special_char = False self.original_layout = layout self.original_layout.configure_specials_key(self) self.special_char_layout = special_char_layout self.special_char_layout.configure_specials_key(self) synchronizeLayout(self.original_layout, self.special_char_layout, self.surface.get_size()) self.set_layout(layout) def invalidate(self): """ Invalidates keyboard state, reset layout and redraw. """ self.layout.invalidate() self.draw() def set_layout(self, layout): """Sets the layout this keyboard work with. Keyboard is invalidate by this action and redraw itself. :param layout: Layout to set. """ self.layout = layout self.invalidate() def enable(self): """ Sets this keyboard as active. """ self.state = 1 self.invalidate() def disable(self): """ Sets this keyboard as non active. """ self.state = 0 def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key) def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate() def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate() def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.type == KEYDOWN: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) elif event.type == KEYUP: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key) def on_key_down(self, key): """Process key down event by pressing the given key. :param key: Key that receives the key down event. """ self.set_key_state(key, 1) self.last_pressed = key def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardRenderer.draw_key
python
def draw_key(self, surface, key): if isinstance(key, VSpaceKey): self.draw_space_key(surface, key) elif isinstance(key, VBackKey): self.draw_back_key(surface, key) elif isinstance(key, VUppercaseKey): self.draw_uppercase_key(surface, key) elif isinstance(key, VSpecialCharKey): self.draw_special_char_key(surface, key) else: self.draw_character_key(surface, key)
Default drawing method for key. Draw the key accordingly to it type. :param surface: Surface background should be drawn in. :param key: Target key to be drawn.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L74-L91
null
class VKeyboardRenderer(object): """A VKeyboardRenderer is in charge of keyboard rendering. It handles keyboard rendering properties such as color or padding, and provides two rendering methods : one for the keyboard background and another one the the key rendering. .. note:: A DEFAULT style instance is available as class attribute. """ def __init__(self, font, keyboard_background_color, key_background_color, text_color, special_key_background_color=None): """VKeyboardStyle default constructor. :param font: Used font for rendering key. :param keyboard_background_color: Background color use for the keyboard. :param key_background_color: Tuple of background color for key (one value per state). :param text_color: Tuple of key text color (one value per state). :param special_key_background_color: Background color for special key if required. """ self.font = font self.keyboard_background_color = keyboard_background_color self.key_background_color = key_background_color self.special_key_background_color = special_key_background_color self.text_color = text_color def draw_background(self, surface, position, size): """Default drawing method for background. Background is drawn as a simple rectangle filled using this style background color attribute. :param surface: Surface background should be drawn in. :param position: Surface relative position the keyboard should be drawn at. :param size: Expected size of the drawn keyboard. """ pygame.draw.rect(surface, self.keyboard_background_color, position + size) def draw_character_key(self, surface, key, special=False): """Default drawing method for key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. :param special: BOolean flag that indicates if the drawn key should use special background color if available. """ background_color = self.key_background_color if special and self.special_key_background_color is not None: background_color = self.special_key_background_color pygame.draw.rect(surface, background_color[key.state], key.position + key.size) size = self.font.size(key.value) x = key.position[0] + ((key.size[0] - size[0]) / 2) y = key.position[1] + ((key.size[1] - size[1]) / 2) surface.blit(self.font.render(key.value, 1, self.text_color[key.state], None), (x, y)) def draw_space_key(self, surface, key): """Default drawing method space key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, False) def draw_back_key(self, surface, key): """Default drawing method for back key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, True) def draw_uppercase_key(self, surface, key): """Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'\u21e7' if key.is_activated(): key.value = u'\u21ea' self.draw_character_key(surface, key, True) def draw_special_char_key(self, surface, key): """Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'#' if key.is_activated(): key.value = u'Ab' self.draw_character_key(surface, key, True)
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardRenderer.draw_character_key
python
def draw_character_key(self, surface, key, special=False): background_color = self.key_background_color if special and self.special_key_background_color is not None: background_color = self.special_key_background_color pygame.draw.rect(surface, background_color[key.state], key.position + key.size) size = self.font.size(key.value) x = key.position[0] + ((key.size[0] - size[0]) / 2) y = key.position[1] + ((key.size[1] - size[1]) / 2) surface.blit(self.font.render(key.value, 1, self.text_color[key.state], None), (x, y))
Default drawing method for key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. :param special: BOolean flag that indicates if the drawn key should use special background color if available.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L93-L111
null
class VKeyboardRenderer(object): """A VKeyboardRenderer is in charge of keyboard rendering. It handles keyboard rendering properties such as color or padding, and provides two rendering methods : one for the keyboard background and another one the the key rendering. .. note:: A DEFAULT style instance is available as class attribute. """ def __init__(self, font, keyboard_background_color, key_background_color, text_color, special_key_background_color=None): """VKeyboardStyle default constructor. :param font: Used font for rendering key. :param keyboard_background_color: Background color use for the keyboard. :param key_background_color: Tuple of background color for key (one value per state). :param text_color: Tuple of key text color (one value per state). :param special_key_background_color: Background color for special key if required. """ self.font = font self.keyboard_background_color = keyboard_background_color self.key_background_color = key_background_color self.special_key_background_color = special_key_background_color self.text_color = text_color def draw_background(self, surface, position, size): """Default drawing method for background. Background is drawn as a simple rectangle filled using this style background color attribute. :param surface: Surface background should be drawn in. :param position: Surface relative position the keyboard should be drawn at. :param size: Expected size of the drawn keyboard. """ pygame.draw.rect(surface, self.keyboard_background_color, position + size) def draw_key(self, surface, key): """Default drawing method for key. Draw the key accordingly to it type. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ if isinstance(key, VSpaceKey): self.draw_space_key(surface, key) elif isinstance(key, VBackKey): self.draw_back_key(surface, key) elif isinstance(key, VUppercaseKey): self.draw_uppercase_key(surface, key) elif isinstance(key, VSpecialCharKey): self.draw_special_char_key(surface, key) else: self.draw_character_key(surface, key) def draw_space_key(self, surface, key): """Default drawing method space key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, False) def draw_back_key(self, surface, key): """Default drawing method for back key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, True) def draw_uppercase_key(self, surface, key): """Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'\u21e7' if key.is_activated(): key.value = u'\u21ea' self.draw_character_key(surface, key, True) def draw_special_char_key(self, surface, key): """Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'#' if key.is_activated(): key.value = u'Ab' self.draw_character_key(surface, key, True)
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardRenderer.draw_uppercase_key
python
def draw_uppercase_key(self, surface, key): key.value = u'\u21e7' if key.is_activated(): key.value = u'\u21ea' self.draw_character_key(surface, key, True)
Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L133-L142
null
class VKeyboardRenderer(object): """A VKeyboardRenderer is in charge of keyboard rendering. It handles keyboard rendering properties such as color or padding, and provides two rendering methods : one for the keyboard background and another one the the key rendering. .. note:: A DEFAULT style instance is available as class attribute. """ def __init__(self, font, keyboard_background_color, key_background_color, text_color, special_key_background_color=None): """VKeyboardStyle default constructor. :param font: Used font for rendering key. :param keyboard_background_color: Background color use for the keyboard. :param key_background_color: Tuple of background color for key (one value per state). :param text_color: Tuple of key text color (one value per state). :param special_key_background_color: Background color for special key if required. """ self.font = font self.keyboard_background_color = keyboard_background_color self.key_background_color = key_background_color self.special_key_background_color = special_key_background_color self.text_color = text_color def draw_background(self, surface, position, size): """Default drawing method for background. Background is drawn as a simple rectangle filled using this style background color attribute. :param surface: Surface background should be drawn in. :param position: Surface relative position the keyboard should be drawn at. :param size: Expected size of the drawn keyboard. """ pygame.draw.rect(surface, self.keyboard_background_color, position + size) def draw_key(self, surface, key): """Default drawing method for key. Draw the key accordingly to it type. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ if isinstance(key, VSpaceKey): self.draw_space_key(surface, key) elif isinstance(key, VBackKey): self.draw_back_key(surface, key) elif isinstance(key, VUppercaseKey): self.draw_uppercase_key(surface, key) elif isinstance(key, VSpecialCharKey): self.draw_special_char_key(surface, key) else: self.draw_character_key(surface, key) def draw_character_key(self, surface, key, special=False): """Default drawing method for key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. :param special: BOolean flag that indicates if the drawn key should use special background color if available. """ background_color = self.key_background_color if special and self.special_key_background_color is not None: background_color = self.special_key_background_color pygame.draw.rect(surface, background_color[key.state], key.position + key.size) size = self.font.size(key.value) x = key.position[0] + ((key.size[0] - size[0]) / 2) y = key.position[1] + ((key.size[1] - size[1]) / 2) surface.blit(self.font.render(key.value, 1, self.text_color[key.state], None), (x, y)) def draw_space_key(self, surface, key): """Default drawing method space key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, False) def draw_back_key(self, surface, key): """Default drawing method for back key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, True) def draw_special_char_key(self, surface, key): """Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'#' if key.is_activated(): key.value = u'Ab' self.draw_character_key(surface, key, True)
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardRenderer.draw_special_char_key
python
def draw_special_char_key(self, surface, key): key.value = u'#' if key.is_activated(): key.value = u'Ab' self.draw_character_key(surface, key, True)
Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L144-L153
null
class VKeyboardRenderer(object): """A VKeyboardRenderer is in charge of keyboard rendering. It handles keyboard rendering properties such as color or padding, and provides two rendering methods : one for the keyboard background and another one the the key rendering. .. note:: A DEFAULT style instance is available as class attribute. """ def __init__(self, font, keyboard_background_color, key_background_color, text_color, special_key_background_color=None): """VKeyboardStyle default constructor. :param font: Used font for rendering key. :param keyboard_background_color: Background color use for the keyboard. :param key_background_color: Tuple of background color for key (one value per state). :param text_color: Tuple of key text color (one value per state). :param special_key_background_color: Background color for special key if required. """ self.font = font self.keyboard_background_color = keyboard_background_color self.key_background_color = key_background_color self.special_key_background_color = special_key_background_color self.text_color = text_color def draw_background(self, surface, position, size): """Default drawing method for background. Background is drawn as a simple rectangle filled using this style background color attribute. :param surface: Surface background should be drawn in. :param position: Surface relative position the keyboard should be drawn at. :param size: Expected size of the drawn keyboard. """ pygame.draw.rect(surface, self.keyboard_background_color, position + size) def draw_key(self, surface, key): """Default drawing method for key. Draw the key accordingly to it type. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ if isinstance(key, VSpaceKey): self.draw_space_key(surface, key) elif isinstance(key, VBackKey): self.draw_back_key(surface, key) elif isinstance(key, VUppercaseKey): self.draw_uppercase_key(surface, key) elif isinstance(key, VSpecialCharKey): self.draw_special_char_key(surface, key) else: self.draw_character_key(surface, key) def draw_character_key(self, surface, key, special=False): """Default drawing method for key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. :param special: BOolean flag that indicates if the drawn key should use special background color if available. """ background_color = self.key_background_color if special and self.special_key_background_color is not None: background_color = self.special_key_background_color pygame.draw.rect(surface, background_color[key.state], key.position + key.size) size = self.font.size(key.value) x = key.position[0] + ((key.size[0] - size[0]) / 2) y = key.position[1] + ((key.size[1] - size[1]) / 2) surface.blit(self.font.render(key.value, 1, self.text_color[key.state], None), (x, y)) def draw_space_key(self, surface, key): """Default drawing method space key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, False) def draw_back_key(self, surface, key): """Default drawing method for back key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ self.draw_character_key(surface, key, True) def draw_uppercase_key(self, surface, key): """Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'\u21e7' if key.is_activated(): key.value = u'\u21ea' self.draw_character_key(surface, key, True)
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKey.is_touched
python
def is_touched(self, position): return position[0] >= self.position[0] and position[0] <= self.position[0]+ self.size[0]
Hit detection method. Indicates if this key has been hit by a touch / click event at the given position. :param position: Event position. :returns: True is the given position collide this key, False otherwise.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L188-L196
null
class VKey(object): """Simple key holder class. Holds key information (its value), as it's state, 1 for pressed, 0 for released. Also contains it size / position properties. """ def __init__(self, value): """Default key constructor. :param value: Value of this key which also is the label displayed to the screen. """ self.state = 0 self.value = value self.position = (0, 0) self.size = (0, 0) def set_size(self, size): """Sets the size of this key. :param size: Size of this key. """ self.size = (size, size) def is_touched(self, position): """Hit detection method. Indicates if this key has been hit by a touch / click event at the given position. :param position: Event position. :returns: True is the given position collide this key, False otherwise. """ return position[0] >= self.position[0] and position[0] <= self.position[0]+ self.size[0] def update_buffer(self, buffer): """Text update method. Aims to be called internally when a key collision has been detected. Updates and returns the given buffer using this key value. :param buffer: Buffer to be updated. :returns: Updated buffer value. """ return buffer + self.value
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyRow.add_key
python
def add_key(self, key, first=False): if first: self.keys = [key] + self.keys else: self.keys.append(key) if isinstance(key, VSpaceKey): self.space = key
Adds the given key to this row. :param key: Key to be added to this row. :param first: BOolean flag that indicates if key is added at the beginning or at the end.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L323-L334
null
class VKeyRow(object): """A VKeyRow defines a keyboard row which is composed of a list of VKey. This class aims to be created internally after parsing a keyboard layout model. It is used to optimize collision detection, by first checking row collision, then internal row key detection. """ def __init__(self): """ Default row constructor. """ self.keys = [] self.y = -1 self.height = 0 self.space = None def set_size(self, position, size, padding): """Row size setter. The size correspond to the row height, since the row width is constraint to the surface width the associated keyboard belongs. Once size is settled, the size for each child keys is associated. :param position: Position of this row. :param size: Size of the row (height) :param padding: Padding between key. """ self.height = size self.position = position x = position[0] for key in self.keys: key.set_size(size) key.position = (x, position[1]) x += padding + key.size[0] def __contains__(self, position): """Indicates if the given position collide this row. :param position: Position to check againt this row. :returns: True if the given position collide this row, False otherwise. """ return position[1] >= self.position[1] and position[1] <= self.position[1] + self.height def __len__(self): """len() operator overload. :returns: Number of keys thi row contains. """ return len(self.keys)
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyRow.set_size
python
def set_size(self, position, size, padding): self.height = size self.position = position x = position[0] for key in self.keys: key.set_size(size) key.position = (x, position[1]) x += padding + key.size[0]
Row size setter. The size correspond to the row height, since the row width is constraint to the surface width the associated keyboard belongs. Once size is settled, the size for each child keys is associated. :param position: Position of this row. :param size: Size of the row (height) :param padding: Padding between key.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L336-L353
null
class VKeyRow(object): """A VKeyRow defines a keyboard row which is composed of a list of VKey. This class aims to be created internally after parsing a keyboard layout model. It is used to optimize collision detection, by first checking row collision, then internal row key detection. """ def __init__(self): """ Default row constructor. """ self.keys = [] self.y = -1 self.height = 0 self.space = None def add_key(self, key, first=False): """Adds the given key to this row. :param key: Key to be added to this row. :param first: BOolean flag that indicates if key is added at the beginning or at the end. """ if first: self.keys = [key] + self.keys else: self.keys.append(key) if isinstance(key, VSpaceKey): self.space = key def set_size(self, position, size, padding): """Row size setter. The size correspond to the row height, since the row width is constraint to the surface width the associated keyboard belongs. Once size is settled, the size for each child keys is associated. :param position: Position of this row. :param size: Size of the row (height) :param padding: Padding between key. """ self.height = size self.position = position x = position[0] for key in self.keys: key.set_size(size) key.position = (x, position[1]) x += padding + key.size[0] def __contains__(self, position): """Indicates if the given position collide this row. :param position: Position to check againt this row. :returns: True if the given position collide this row, False otherwise. """ return position[1] >= self.position[1] and position[1] <= self.position[1] + self.height def __len__(self): """len() operator overload. :returns: Number of keys thi row contains. """ return len(self.keys)
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardLayout.configure_specials_key
python
def configure_specials_key(self, keyboard): special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard)) while len(special_keys) > 0: first = False while len(special_keys) > 0 and len(current_row) < max_length: current_row.add_key(special_keys.pop(0), first=first) first = not first if i > 0: i -= 1 current_row = self.rows[i] else: break if self.allow_space: space_length = len(current_row) - len(special_keys) special_row.add_key(VSpaceKey(space_length)) first = True # Adding left to the special bar. while len(special_keys) > 0: special_row.add_key(special_keys.pop(0), first=first) first = not first if len(special_row) > 0: self.rows.append(special_row)
Configures specials key if needed. :param keyboard: Keyboard instance this layout belong.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L421-L452
null
class VKeyboardLayout(object): """Keyboard layout class. A keyboard layout is built using layout model which consists in an list of supported character. Such list item as simple string containing characters assigned to a row. An erasing key is inserted automatically to the first row. If allowUpperCase flag is True, then an upper case key will be inserted at the beginning of the second row. If allowSpecialChars flag is True, then an special characters / number key will be inserted at the beginning of the third row. Pressing this key will switch the associated keyboard current layout. """ """ Azerty layout. """ AZERTY = ['1234567890', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'] """ Number only layout. """ NUMBER = ['123', '456', '789', '0'] """ """ SPECIAL = [u'&é"\'(§è!çà)', u'°_-^$¨*ù`%£', u',;:=?.@+<>#', u'[]{}/\\|'] # TODO : Insert special characters layout which include number. def __init__(self, model, key_size=None, padding=5, allow_uppercase=True, allow_special_chars=True, allow_space=True): """Default constructor. Initializes layout rows. :param model: Layout model to use. :param key_size Size of the key, if not specified will be computed dynamically. :param padding: Padding between key (work horizontally as vertically). :param allowUpperCase: Boolean flag that indicates usage of upper case switching key. :param allowSpecialChars: Boolean flag that indicates usage of special char switching key. :param allowSpace: Boolean flag that indicates usage of space bar. """ self.rows = [] self.key_size = key_size self.padding = padding self.allow_space = allow_space self.allow_uppercase = allow_uppercase self.allow_special_chars = allow_special_chars for model_row in model: row = VKeyRow() for value in model_row: row.add_key(VKey(value)) self.rows.append(row) self.max_length = len(max(self.rows, key=len)) if self.max_length == 0: raise ValueError('Empty layout model provided') def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size) def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surface_size[0] - width) / 2 if row.space is not None: x -= ((row.space.length - 1) * self.key_size) / 2 row.set_size((x, y), self.key_size, self.padding) y += self.padding + self.key_size def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0 def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower() def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardLayout.configure_bound
python
def configure_bound(self, surface_size): r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size)
Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L454-L472
null
class VKeyboardLayout(object): """Keyboard layout class. A keyboard layout is built using layout model which consists in an list of supported character. Such list item as simple string containing characters assigned to a row. An erasing key is inserted automatically to the first row. If allowUpperCase flag is True, then an upper case key will be inserted at the beginning of the second row. If allowSpecialChars flag is True, then an special characters / number key will be inserted at the beginning of the third row. Pressing this key will switch the associated keyboard current layout. """ """ Azerty layout. """ AZERTY = ['1234567890', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'] """ Number only layout. """ NUMBER = ['123', '456', '789', '0'] """ """ SPECIAL = [u'&é"\'(§è!çà)', u'°_-^$¨*ù`%£', u',;:=?.@+<>#', u'[]{}/\\|'] # TODO : Insert special characters layout which include number. def __init__(self, model, key_size=None, padding=5, allow_uppercase=True, allow_special_chars=True, allow_space=True): """Default constructor. Initializes layout rows. :param model: Layout model to use. :param key_size Size of the key, if not specified will be computed dynamically. :param padding: Padding between key (work horizontally as vertically). :param allowUpperCase: Boolean flag that indicates usage of upper case switching key. :param allowSpecialChars: Boolean flag that indicates usage of special char switching key. :param allowSpace: Boolean flag that indicates usage of space bar. """ self.rows = [] self.key_size = key_size self.padding = padding self.allow_space = allow_space self.allow_uppercase = allow_uppercase self.allow_special_chars = allow_special_chars for model_row in model: row = VKeyRow() for value in model_row: row.add_key(VKey(value)) self.rows.append(row) self.max_length = len(max(self.rows, key=len)) if self.max_length == 0: raise ValueError('Empty layout model provided') def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard)) while len(special_keys) > 0: first = False while len(special_keys) > 0 and len(current_row) < max_length: current_row.add_key(special_keys.pop(0), first=first) first = not first if i > 0: i -= 1 current_row = self.rows[i] else: break if self.allow_space: space_length = len(current_row) - len(special_keys) special_row.add_key(VSpaceKey(space_length)) first = True # Adding left to the special bar. while len(special_keys) > 0: special_row.add_key(special_keys.pop(0), first=first) first = not first if len(special_row) > 0: self.rows.append(special_row) def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size) def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surface_size[0] - width) / 2 if row.space is not None: x -= ((row.space.length - 1) * self.key_size) / 2 row.set_size((x, y), self.key_size, self.padding) y += self.padding + self.key_size def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0 def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower() def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardLayout.set_size
python
def set_size(self, size, surface_size): self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surface_size[0] - width) / 2 if row.space is not None: x -= ((row.space.length - 1) * self.key_size) / 2 row.set_size((x, y), self.key_size, self.padding) y += self.padding + self.key_size
Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L474-L492
null
class VKeyboardLayout(object): """Keyboard layout class. A keyboard layout is built using layout model which consists in an list of supported character. Such list item as simple string containing characters assigned to a row. An erasing key is inserted automatically to the first row. If allowUpperCase flag is True, then an upper case key will be inserted at the beginning of the second row. If allowSpecialChars flag is True, then an special characters / number key will be inserted at the beginning of the third row. Pressing this key will switch the associated keyboard current layout. """ """ Azerty layout. """ AZERTY = ['1234567890', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'] """ Number only layout. """ NUMBER = ['123', '456', '789', '0'] """ """ SPECIAL = [u'&é"\'(§è!çà)', u'°_-^$¨*ù`%£', u',;:=?.@+<>#', u'[]{}/\\|'] # TODO : Insert special characters layout which include number. def __init__(self, model, key_size=None, padding=5, allow_uppercase=True, allow_special_chars=True, allow_space=True): """Default constructor. Initializes layout rows. :param model: Layout model to use. :param key_size Size of the key, if not specified will be computed dynamically. :param padding: Padding between key (work horizontally as vertically). :param allowUpperCase: Boolean flag that indicates usage of upper case switching key. :param allowSpecialChars: Boolean flag that indicates usage of special char switching key. :param allowSpace: Boolean flag that indicates usage of space bar. """ self.rows = [] self.key_size = key_size self.padding = padding self.allow_space = allow_space self.allow_uppercase = allow_uppercase self.allow_special_chars = allow_special_chars for model_row in model: row = VKeyRow() for value in model_row: row.add_key(VKey(value)) self.rows.append(row) self.max_length = len(max(self.rows, key=len)) if self.max_length == 0: raise ValueError('Empty layout model provided') def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard)) while len(special_keys) > 0: first = False while len(special_keys) > 0 and len(current_row) < max_length: current_row.add_key(special_keys.pop(0), first=first) first = not first if i > 0: i -= 1 current_row = self.rows[i] else: break if self.allow_space: space_length = len(current_row) - len(special_keys) special_row.add_key(VSpaceKey(space_length)) first = True # Adding left to the special bar. while len(special_keys) > 0: special_row.add_key(special_keys.pop(0), first=first) first = not first if len(special_row) > 0: self.rows.append(special_row) def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size) def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0 def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower() def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardLayout.invalidate
python
def invalidate(self): for row in self.rows: for key in row.keys: key.state = 0
Rests all keys states.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L494-L498
null
class VKeyboardLayout(object): """Keyboard layout class. A keyboard layout is built using layout model which consists in an list of supported character. Such list item as simple string containing characters assigned to a row. An erasing key is inserted automatically to the first row. If allowUpperCase flag is True, then an upper case key will be inserted at the beginning of the second row. If allowSpecialChars flag is True, then an special characters / number key will be inserted at the beginning of the third row. Pressing this key will switch the associated keyboard current layout. """ """ Azerty layout. """ AZERTY = ['1234567890', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'] """ Number only layout. """ NUMBER = ['123', '456', '789', '0'] """ """ SPECIAL = [u'&é"\'(§è!çà)', u'°_-^$¨*ù`%£', u',;:=?.@+<>#', u'[]{}/\\|'] # TODO : Insert special characters layout which include number. def __init__(self, model, key_size=None, padding=5, allow_uppercase=True, allow_special_chars=True, allow_space=True): """Default constructor. Initializes layout rows. :param model: Layout model to use. :param key_size Size of the key, if not specified will be computed dynamically. :param padding: Padding between key (work horizontally as vertically). :param allowUpperCase: Boolean flag that indicates usage of upper case switching key. :param allowSpecialChars: Boolean flag that indicates usage of special char switching key. :param allowSpace: Boolean flag that indicates usage of space bar. """ self.rows = [] self.key_size = key_size self.padding = padding self.allow_space = allow_space self.allow_uppercase = allow_uppercase self.allow_special_chars = allow_special_chars for model_row in model: row = VKeyRow() for value in model_row: row.add_key(VKey(value)) self.rows.append(row) self.max_length = len(max(self.rows, key=len)) if self.max_length == 0: raise ValueError('Empty layout model provided') def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard)) while len(special_keys) > 0: first = False while len(special_keys) > 0 and len(current_row) < max_length: current_row.add_key(special_keys.pop(0), first=first) first = not first if i > 0: i -= 1 current_row = self.rows[i] else: break if self.allow_space: space_length = len(current_row) - len(special_keys) special_row.add_key(VSpaceKey(space_length)) first = True # Adding left to the special bar. while len(special_keys) > 0: special_row.add_key(special_keys.pop(0), first=first) first = not first if len(special_row) > 0: self.rows.append(special_row) def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size) def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surface_size[0] - width) / 2 if row.space is not None: x -= ((row.space.length - 1) * self.key_size) / 2 row.set_size((x, y), self.key_size, self.padding) y += self.padding + self.key_size def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower() def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardLayout.set_uppercase
python
def set_uppercase(self, uppercase): for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower()
Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L500-L511
null
class VKeyboardLayout(object): """Keyboard layout class. A keyboard layout is built using layout model which consists in an list of supported character. Such list item as simple string containing characters assigned to a row. An erasing key is inserted automatically to the first row. If allowUpperCase flag is True, then an upper case key will be inserted at the beginning of the second row. If allowSpecialChars flag is True, then an special characters / number key will be inserted at the beginning of the third row. Pressing this key will switch the associated keyboard current layout. """ """ Azerty layout. """ AZERTY = ['1234567890', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'] """ Number only layout. """ NUMBER = ['123', '456', '789', '0'] """ """ SPECIAL = [u'&é"\'(§è!çà)', u'°_-^$¨*ù`%£', u',;:=?.@+<>#', u'[]{}/\\|'] # TODO : Insert special characters layout which include number. def __init__(self, model, key_size=None, padding=5, allow_uppercase=True, allow_special_chars=True, allow_space=True): """Default constructor. Initializes layout rows. :param model: Layout model to use. :param key_size Size of the key, if not specified will be computed dynamically. :param padding: Padding between key (work horizontally as vertically). :param allowUpperCase: Boolean flag that indicates usage of upper case switching key. :param allowSpecialChars: Boolean flag that indicates usage of special char switching key. :param allowSpace: Boolean flag that indicates usage of space bar. """ self.rows = [] self.key_size = key_size self.padding = padding self.allow_space = allow_space self.allow_uppercase = allow_uppercase self.allow_special_chars = allow_special_chars for model_row in model: row = VKeyRow() for value in model_row: row.add_key(VKey(value)) self.rows.append(row) self.max_length = len(max(self.rows, key=len)) if self.max_length == 0: raise ValueError('Empty layout model provided') def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard)) while len(special_keys) > 0: first = False while len(special_keys) > 0 and len(current_row) < max_length: current_row.add_key(special_keys.pop(0), first=first) first = not first if i > 0: i -= 1 current_row = self.rows[i] else: break if self.allow_space: space_length = len(current_row) - len(special_keys) special_row.add_key(VSpaceKey(space_length)) first = True # Adding left to the special bar. while len(special_keys) > 0: special_row.add_key(special_keys.pop(0), first=first) first = not first if len(special_row) > 0: self.rows.append(special_row) def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size) def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surface_size[0] - width) / 2 if row.space is not None: x -= ((row.space.length - 1) * self.key_size) / 2 row.set_size((x, y), self.key_size, self.padding) y += self.padding + self.key_size def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0 def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardLayout.get_key_at
python
def get_key_at(self, position): for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L513-L524
null
class VKeyboardLayout(object): """Keyboard layout class. A keyboard layout is built using layout model which consists in an list of supported character. Such list item as simple string containing characters assigned to a row. An erasing key is inserted automatically to the first row. If allowUpperCase flag is True, then an upper case key will be inserted at the beginning of the second row. If allowSpecialChars flag is True, then an special characters / number key will be inserted at the beginning of the third row. Pressing this key will switch the associated keyboard current layout. """ """ Azerty layout. """ AZERTY = ['1234567890', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'] """ Number only layout. """ NUMBER = ['123', '456', '789', '0'] """ """ SPECIAL = [u'&é"\'(§è!çà)', u'°_-^$¨*ù`%£', u',;:=?.@+<>#', u'[]{}/\\|'] # TODO : Insert special characters layout which include number. def __init__(self, model, key_size=None, padding=5, allow_uppercase=True, allow_special_chars=True, allow_space=True): """Default constructor. Initializes layout rows. :param model: Layout model to use. :param key_size Size of the key, if not specified will be computed dynamically. :param padding: Padding between key (work horizontally as vertically). :param allowUpperCase: Boolean flag that indicates usage of upper case switching key. :param allowSpecialChars: Boolean flag that indicates usage of special char switching key. :param allowSpace: Boolean flag that indicates usage of space bar. """ self.rows = [] self.key_size = key_size self.padding = padding self.allow_space = allow_space self.allow_uppercase = allow_uppercase self.allow_special_chars = allow_special_chars for model_row in model: row = VKeyRow() for value in model_row: row.add_key(VKey(value)) self.rows.append(row) self.max_length = len(max(self.rows, key=len)) if self.max_length == 0: raise ValueError('Empty layout model provided') def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard)) if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard)) while len(special_keys) > 0: first = False while len(special_keys) > 0 and len(current_row) < max_length: current_row.add_key(special_keys.pop(0), first=first) first = not first if i > 0: i -= 1 current_row = self.rows[i] else: break if self.allow_space: space_length = len(current_row) - len(special_keys) special_row.add_key(VSpaceKey(space_length)) first = True # Adding left to the special bar. while len(special_keys) > 0: special_row.add_key(special_keys.pop(0), first=first) first = not first if len(special_row) > 0: self.rows.append(special_row) def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows) max_length = self.max_length if self.key_size is None: self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length height = self.key_size * r + self.padding * (r + 1) if height >= surface_size[1] / 2: logger.warning('Computed keyboard height outbound target surface, reducing key_size to match') self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r height = self.key_size * r + self.padding * (r + 1) logger.warning('Normalized key_size to %spx' % self.key_size) self.set_size((surface_size[0], height), surface_size) def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1] + self.padding max_length = self.max_length for row in self.rows: r = len(row) width = (r * self.key_size) + ((r + 1) * self.padding) x = (surface_size[0] - width) / 2 if row.space is not None: x -= ((row.space.length - 1) * self.key_size) / 2 row.set_size((x, y), self.key_size, self.padding) y += self.padding + self.key_size def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0 def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower() def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboard.draw
python
def draw(self): if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key)
Draw the virtual keyboard into the delegate surface object if enabled.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L604-L610
null
class VKeyboard(object): """Virtual Keyboard class. A virtual keyboard consists in a VKeyboardLayout that acts as the keyboard model and a VKeyboardRenderer which is in charge of drawing keyboard component to screen. """ def __init__(self, surface, text_consumer, layout, special_char_layout=VKeyboardLayout(VKeyboardLayout.SPECIAL), renderer=VKeyboardRenderer.DEFAULT): """Default constructor. :param surface: Surface this keyboard will be displayed at. :param text_consumer: Consumer that process text for each update. :param layout: Layout this keyboard will use. :param special_char_layout: Alternative layout to use, using VKeyboardLayout.SPECIAL if not specified. :param renderer: Keyboard renderer instance, using VKeyboardStyle.DEFAULT if not specified. """ self.surface = surface self.text_consumer = text_consumer self.renderer = renderer self.buffer = u'' self.state = 0 self.last_pressed = None self.uppercase = False self.special_char = False self.original_layout = layout self.original_layout.configure_specials_key(self) self.special_char_layout = special_char_layout self.special_char_layout.configure_specials_key(self) synchronizeLayout(self.original_layout, self.special_char_layout, self.surface.get_size()) self.set_layout(layout) def invalidate(self): """ Invalidates keyboard state, reset layout and redraw. """ self.layout.invalidate() self.draw() def set_layout(self, layout): """Sets the layout this keyboard work with. Keyboard is invalidate by this action and redraw itself. :param layout: Layout to set. """ self.layout = layout self.invalidate() def enable(self): """ Sets this keyboard as active. """ self.state = 1 self.invalidate() def disable(self): """ Sets this keyboard as non active. """ self.state = 0 def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate() def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate() def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.type == KEYDOWN: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) elif event.type == KEYUP: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key) def on_key_down(self, key): """Process key down event by pressing the given key. :param key: Key that receives the key down event. """ self.set_key_state(key, 1) self.last_pressed = key def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboard.on_uppercase
python
def on_uppercase(self): self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate()
Uppercase key press handler.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L612-L617
null
class VKeyboard(object): """Virtual Keyboard class. A virtual keyboard consists in a VKeyboardLayout that acts as the keyboard model and a VKeyboardRenderer which is in charge of drawing keyboard component to screen. """ def __init__(self, surface, text_consumer, layout, special_char_layout=VKeyboardLayout(VKeyboardLayout.SPECIAL), renderer=VKeyboardRenderer.DEFAULT): """Default constructor. :param surface: Surface this keyboard will be displayed at. :param text_consumer: Consumer that process text for each update. :param layout: Layout this keyboard will use. :param special_char_layout: Alternative layout to use, using VKeyboardLayout.SPECIAL if not specified. :param renderer: Keyboard renderer instance, using VKeyboardStyle.DEFAULT if not specified. """ self.surface = surface self.text_consumer = text_consumer self.renderer = renderer self.buffer = u'' self.state = 0 self.last_pressed = None self.uppercase = False self.special_char = False self.original_layout = layout self.original_layout.configure_specials_key(self) self.special_char_layout = special_char_layout self.special_char_layout.configure_specials_key(self) synchronizeLayout(self.original_layout, self.special_char_layout, self.surface.get_size()) self.set_layout(layout) def invalidate(self): """ Invalidates keyboard state, reset layout and redraw. """ self.layout.invalidate() self.draw() def set_layout(self, layout): """Sets the layout this keyboard work with. Keyboard is invalidate by this action and redraw itself. :param layout: Layout to set. """ self.layout = layout self.invalidate() def enable(self): """ Sets this keyboard as active. """ self.state = 1 self.invalidate() def disable(self): """ Sets this keyboard as non active. """ self.state = 0 def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key) def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate() def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.type == KEYDOWN: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) elif event.type == KEYUP: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key) def on_key_down(self, key): """Process key down event by pressing the given key. :param key: Key that receives the key down event. """ self.set_key_state(key, 1) self.last_pressed = key def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboard.on_special_char
python
def on_special_char(self): self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate()
Special char key press handler.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L619-L626
null
class VKeyboard(object): """Virtual Keyboard class. A virtual keyboard consists in a VKeyboardLayout that acts as the keyboard model and a VKeyboardRenderer which is in charge of drawing keyboard component to screen. """ def __init__(self, surface, text_consumer, layout, special_char_layout=VKeyboardLayout(VKeyboardLayout.SPECIAL), renderer=VKeyboardRenderer.DEFAULT): """Default constructor. :param surface: Surface this keyboard will be displayed at. :param text_consumer: Consumer that process text for each update. :param layout: Layout this keyboard will use. :param special_char_layout: Alternative layout to use, using VKeyboardLayout.SPECIAL if not specified. :param renderer: Keyboard renderer instance, using VKeyboardStyle.DEFAULT if not specified. """ self.surface = surface self.text_consumer = text_consumer self.renderer = renderer self.buffer = u'' self.state = 0 self.last_pressed = None self.uppercase = False self.special_char = False self.original_layout = layout self.original_layout.configure_specials_key(self) self.special_char_layout = special_char_layout self.special_char_layout.configure_specials_key(self) synchronizeLayout(self.original_layout, self.special_char_layout, self.surface.get_size()) self.set_layout(layout) def invalidate(self): """ Invalidates keyboard state, reset layout and redraw. """ self.layout.invalidate() self.draw() def set_layout(self, layout): """Sets the layout this keyboard work with. Keyboard is invalidate by this action and redraw itself. :param layout: Layout to set. """ self.layout = layout self.invalidate() def enable(self): """ Sets this keyboard as active. """ self.state = 1 self.invalidate() def disable(self): """ Sets this keyboard as non active. """ self.state = 0 def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key) def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate() def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.type == KEYDOWN: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) elif event.type == KEYUP: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key) def on_key_down(self, key): """Process key down event by pressing the given key. :param key: Key that receives the key down event. """ self.set_key_state(key, 1) self.last_pressed = key def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboard.on_event
python
def on_event(self, event): if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.type == KEYDOWN: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) elif event.type == KEYUP: value = pygame.key.name(event.key)
Pygame event processing callback method. :param event: Event to process.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L628-L644
null
class VKeyboard(object): """Virtual Keyboard class. A virtual keyboard consists in a VKeyboardLayout that acts as the keyboard model and a VKeyboardRenderer which is in charge of drawing keyboard component to screen. """ def __init__(self, surface, text_consumer, layout, special_char_layout=VKeyboardLayout(VKeyboardLayout.SPECIAL), renderer=VKeyboardRenderer.DEFAULT): """Default constructor. :param surface: Surface this keyboard will be displayed at. :param text_consumer: Consumer that process text for each update. :param layout: Layout this keyboard will use. :param special_char_layout: Alternative layout to use, using VKeyboardLayout.SPECIAL if not specified. :param renderer: Keyboard renderer instance, using VKeyboardStyle.DEFAULT if not specified. """ self.surface = surface self.text_consumer = text_consumer self.renderer = renderer self.buffer = u'' self.state = 0 self.last_pressed = None self.uppercase = False self.special_char = False self.original_layout = layout self.original_layout.configure_specials_key(self) self.special_char_layout = special_char_layout self.special_char_layout.configure_specials_key(self) synchronizeLayout(self.original_layout, self.special_char_layout, self.surface.get_size()) self.set_layout(layout) def invalidate(self): """ Invalidates keyboard state, reset layout and redraw. """ self.layout.invalidate() self.draw() def set_layout(self, layout): """Sets the layout this keyboard work with. Keyboard is invalidate by this action and redraw itself. :param layout: Layout to set. """ self.layout = layout self.invalidate() def enable(self): """ Sets this keyboard as active. """ self.state = 1 self.invalidate() def disable(self): """ Sets this keyboard as non active. """ self.state = 0 def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key) def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate() def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate() # TODO : Find from layout (consider checking layout key space ?) def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key) def on_key_down(self, key): """Process key down event by pressing the given key. :param key: Key that receives the key down event. """ self.set_key_state(key, 1) self.last_pressed = key def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboard.set_key_state
python
def set_key_state(self, key, state): key.state = state self.renderer.draw_key(self.surface, key)
Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L647-L654
null
class VKeyboard(object): """Virtual Keyboard class. A virtual keyboard consists in a VKeyboardLayout that acts as the keyboard model and a VKeyboardRenderer which is in charge of drawing keyboard component to screen. """ def __init__(self, surface, text_consumer, layout, special_char_layout=VKeyboardLayout(VKeyboardLayout.SPECIAL), renderer=VKeyboardRenderer.DEFAULT): """Default constructor. :param surface: Surface this keyboard will be displayed at. :param text_consumer: Consumer that process text for each update. :param layout: Layout this keyboard will use. :param special_char_layout: Alternative layout to use, using VKeyboardLayout.SPECIAL if not specified. :param renderer: Keyboard renderer instance, using VKeyboardStyle.DEFAULT if not specified. """ self.surface = surface self.text_consumer = text_consumer self.renderer = renderer self.buffer = u'' self.state = 0 self.last_pressed = None self.uppercase = False self.special_char = False self.original_layout = layout self.original_layout.configure_specials_key(self) self.special_char_layout = special_char_layout self.special_char_layout.configure_specials_key(self) synchronizeLayout(self.original_layout, self.special_char_layout, self.surface.get_size()) self.set_layout(layout) def invalidate(self): """ Invalidates keyboard state, reset layout and redraw. """ self.layout.invalidate() self.draw() def set_layout(self, layout): """Sets the layout this keyboard work with. Keyboard is invalidate by this action and redraw itself. :param layout: Layout to set. """ self.layout = layout self.invalidate() def enable(self): """ Sets this keyboard as active. """ self.state = 1 self.invalidate() def disable(self): """ Sets this keyboard as non active. """ self.state = 0 def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key) def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate() def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate() def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.type == KEYDOWN: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) elif event.type == KEYUP: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) def on_key_down(self, key): """Process key down event by pressing the given key. :param key: Key that receives the key down event. """ self.set_key_state(key, 1) self.last_pressed = key def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboard.on_key_up
python
def on_key_up(self): if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
Process key up event by updating buffer and release key.
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L664-L670
null
class VKeyboard(object): """Virtual Keyboard class. A virtual keyboard consists in a VKeyboardLayout that acts as the keyboard model and a VKeyboardRenderer which is in charge of drawing keyboard component to screen. """ def __init__(self, surface, text_consumer, layout, special_char_layout=VKeyboardLayout(VKeyboardLayout.SPECIAL), renderer=VKeyboardRenderer.DEFAULT): """Default constructor. :param surface: Surface this keyboard will be displayed at. :param text_consumer: Consumer that process text for each update. :param layout: Layout this keyboard will use. :param special_char_layout: Alternative layout to use, using VKeyboardLayout.SPECIAL if not specified. :param renderer: Keyboard renderer instance, using VKeyboardStyle.DEFAULT if not specified. """ self.surface = surface self.text_consumer = text_consumer self.renderer = renderer self.buffer = u'' self.state = 0 self.last_pressed = None self.uppercase = False self.special_char = False self.original_layout = layout self.original_layout.configure_specials_key(self) self.special_char_layout = special_char_layout self.special_char_layout.configure_specials_key(self) synchronizeLayout(self.original_layout, self.special_char_layout, self.surface.get_size()) self.set_layout(layout) def invalidate(self): """ Invalidates keyboard state, reset layout and redraw. """ self.layout.invalidate() self.draw() def set_layout(self, layout): """Sets the layout this keyboard work with. Keyboard is invalidate by this action and redraw itself. :param layout: Layout to set. """ self.layout = layout self.invalidate() def enable(self): """ Sets this keyboard as active. """ self.state = 1 self.invalidate() def disable(self): """ Sets this keyboard as non active. """ self.state = 0 def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key) def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate() def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate() def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.type == KEYDOWN: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) elif event.type == KEYUP: value = pygame.key.name(event.key) # TODO : Find from layout (consider checking layout key space ?) def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key) def on_key_down(self, key): """Process key down event by pressing the given key. :param key: Key that receives the key down event. """ self.set_key_state(key, 1) self.last_pressed = key
ianclegg/ntlmlib
ntlmlib/security.py
Ntlm1Sealing.wrap
python
def wrap(self, message): cipher_text = _Ntlm1Session.encrypt(self, message) signature = _Ntlm1Session.sign(self, message) return cipher_text, signature
NTM GSSwrap() :param message: The message to be encrypted :return: The signed and encrypted message
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/security.py#L170-L178
[ "def sign(self, message):\n # NTLM1 integrity checks use a simple CRC in little endian format, the CRC and Sequence are both\n # encrypted using the weakened session key or user key\n crc = zlib.crc32(message)\n mac = _Ntlm1MessageSignature()\n\n mac['random'] = self._encrypt.update(struct.pack('<i', 0))\n mac['checksum'] = self._encrypt.update(struct.pack('<i', crc))\n mac['sequence'] = self._encrypt.update(struct.pack('<i', self._sequence))\n\n # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 64)\n # Once all fields have been encrypted with the RC4 keystream the random pad is overwritten\n # with 4 zero bytes (some implementations use a pseudo random sequence instead)\n mac['random'] = struct.pack('<i', 0)\n\n # Increment the sequence number after each signature is computed\n self._sequence += 1\n return str(mac)\n", "def encrypt(self, message):\n \"\"\"\n Encrypts the supplied message using NTLM1 Session Security\n :param message: The message to be encrypted\n :return: The signed and encrypted message\n \"\"\"\n return self._encrypt.update(message)\n" ]
class Ntlm1Sealing(_Ntlm1Session): """ """ def __init__(self, flags, session_key): _Ntlm1Session.__init__(self, flags, session_key) def unwrap(self, message, signature): """ NTLM GSSUnwrap() :param message: The message to be encrypted :return: The signed and encrypted message """ plain_text = _Ntlm1Session.decrypt(self, message) _Ntlm1Session.verify(self, plain_text, signature) return plain_text
ianclegg/ntlmlib
ntlmlib/security.py
Ntlm1Sealing.unwrap
python
def unwrap(self, message, signature): plain_text = _Ntlm1Session.decrypt(self, message) _Ntlm1Session.verify(self, plain_text, signature) return plain_text
NTLM GSSUnwrap() :param message: The message to be encrypted :return: The signed and encrypted message
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/security.py#L180-L188
[ "def verify(self, message, signature):\n # Parse the signature header\n mac = _Ntlm1MessageSignature()\n mac.from_string(signature)\n\n # decrypt and then unpack the signature fields in order\n self._decrypt.update(mac['random'])\n crc = struct.unpack('<i', self._decrypt.update(mac['checksum']))[0]\n sequence = struct.unpack('<i', self._decrypt.update(mac['sequence']))[0]\n\n # validate the sequence number is what we expect\n if sequence != self._sequence:\n raise Exception(\"The message was not received in the correct sequence.\")\n\n # validate the supplied checksum matches our computed checksum\n if crc != zlib.crc32(message):\n raise Exception(\"The message has been altered\")\n\n # once more, ensure the sequence number is incremented\n self._sequence += 1\n", "def decrypt(self, message):\n \"\"\"\n Decrypts the supplied message using NTLM1 Session Security\n :param message: The ciphertext to be decrypted\n :return: The original plaintext\n \"\"\"\n return self._decrypt.update(message)\n" ]
class Ntlm1Sealing(_Ntlm1Session): """ """ def __init__(self, flags, session_key): _Ntlm1Session.__init__(self, flags, session_key) def wrap(self, message): """ NTM GSSwrap() :param message: The message to be encrypted :return: The signed and encrypted message """ cipher_text = _Ntlm1Session.encrypt(self, message) signature = _Ntlm1Session.sign(self, message) return cipher_text, signature
ianclegg/ntlmlib
ntlmlib/security.py
_Ntlm2Session._weaken_key
python
def _weaken_key(flags, key): if flags & NegotiateFlag.NTLMSSP_KEY_128: return key if flags & NegotiateFlag.NTLMSSP_NEGOTIATE_56: return key[:7] else: return key[:5]
NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under NTLM2. In this case, the master key is used directly in the generation of subkeys (with no weakening performed). :param flags: The negotiated NTLM flags :return: The 16-byte key to be used to sign messages
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/security.py#L245-L258
null
class _Ntlm2Session(object): """ _ _ _____ _ __ __ ___ | \| |_ _| | | \/ | |_ ) SESSION SECURITY | .` | | | | |__| |\/| | / / Windows NT4 SP4 and later |_|\_| |_| |____|_| |_| /___| This is a newer scheme which can be used with both NTLMv1 and NTLMv2 Authentication. """ client_signing = b"session key to client-to-server signing key magic constant\0" client_sealing = b"session key to client-to-server sealing key magic constant\0" server_signing = b"session key to server-to-client signing key magic constant\0" server_sealing = b"session key to server-to-client sealing key magic constant\0" """ """ def __init__(self, flags, session_key, mode): self.key_exchange = True self.outgoing_sequence = 0 self.incoming_sequence = 0 session_key = _Ntlm2Session._weaken_key(flags, session_key) #logger.debug("Session Key after Weakening: %s", AsHex(session_key)) client_signing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.client_signing) server_signing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.server_signing) client_sealing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.client_sealing) server_sealing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.server_sealing) if mode=='client': self.outgoing_signing_key = client_signing_key self.incoming_signing_key = server_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(client_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(server_arc4, mode=None, backend=default_backend()).decryptor() elif mode=='server': self.outgoing_signing_key = server_signing_key self.incoming_signing_key = client_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(server_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(client_arc4, mode=None, backend=default_backend()).decryptor() #logger.debug("Client Signing Key: %s", AsHex(client_signing_key)) #logger.debug("Server Signing Key: %s", AsHex(server_signing_key)) #logger.debug("Client Sealing Key: %s", AsHex(client_sealing_key)) #logger.debug("Server Sealing Key: %s", AsHex(server_sealing_key)) @staticmethod def _generate_key(material): md5 = hashlib.new('md5') md5.update(material) return md5.digest() @staticmethod def sign(self, message): """ Generates a signature for the supplied message using NTLM2 Session Security Note: [MS-NLMP] Section 3.4.4 The message signature for NTLM with extended session security is a 16-byte value that contains the following components, as described by the NTLMSSP_MESSAGE_SIGNATURE structure: - A 4-byte version-number value that is set to 1 - The first eight bytes of the message's HMAC_MD5 - The 4-byte sequence number (SeqNum) :param message: The message to be signed :return: The signature for supplied message """ hmac_context = hmac.new(self.outgoing_signing_key) hmac_context.update(struct.pack('<i', self.outgoing_sequence) + message) # If a key exchange key is negotiated the first 8 bytes of the HMAC MD5 are encrypted with RC4 if self.key_exchange: checksum = self.outgoing_seal.update(hmac_context.digest()[:8]) else: checksum = hmac_context.digest()[:8] mac = _Ntlm2MessageSignature() mac['checksum'] = struct.unpack('<q', checksum)[0] mac['sequence'] = self.outgoing_sequence #logger.debug("Signing Sequence Number: %s", str(self.outgoing_sequence)) # Increment the sequence number after signing each message self.outgoing_sequence += 1 return str(mac) def verify(self, message, signature): """ Verified the signature attached to the supplied message using NTLM2 Session Security :param message: The message whose signature will verified :return: True if the signature is valid, otherwise False """ # Parse the signature header mac = _Ntlm2MessageSignature() mac.from_string(signature) # validate the sequence if mac['sequence'] != self.incoming_sequence: raise Exception("The message was not received in the correct sequence.") # extract the supplied checksum checksum = struct.pack('<q', mac['checksum']) if self.key_exchange: checksum = self.incoming_seal.update(checksum) # calculate the expected checksum for the message hmac_context = hmac.new(self.incoming_signing_key) hmac_context.update(struct.pack('<i', self.incoming_sequence) + message) expected_checksum = hmac_context.digest()[:8] # validate the supplied checksum is correct if checksum != expected_checksum: raise Exception("The message has been altered") #logger.debug("Verify Sequence Number: %s", AsHex(self.outgoing_sequence)) self.incoming_sequence += 1 def encrypt(self, message): """ Encrypts the supplied message using NTLM2 Session Security :param message: The message to be encrypted :return: The signed and encrypted message """ return self.outgoing_seal.update(message) def decrypt(self, cipher_text): """ Decrypts the supplied message using NTLM2 Session Security :param message: The ciphertext to be decrypted :return: The original plaintext """ return self.incoming_seal.update(cipher_text)
ianclegg/ntlmlib
ntlmlib/security.py
_Ntlm2Session.sign
python
def sign(self, message): hmac_context = hmac.new(self.outgoing_signing_key) hmac_context.update(struct.pack('<i', self.outgoing_sequence) + message) # If a key exchange key is negotiated the first 8 bytes of the HMAC MD5 are encrypted with RC4 if self.key_exchange: checksum = self.outgoing_seal.update(hmac_context.digest()[:8]) else: checksum = hmac_context.digest()[:8] mac = _Ntlm2MessageSignature() mac['checksum'] = struct.unpack('<q', checksum)[0] mac['sequence'] = self.outgoing_sequence #logger.debug("Signing Sequence Number: %s", str(self.outgoing_sequence)) # Increment the sequence number after signing each message self.outgoing_sequence += 1 return str(mac)
Generates a signature for the supplied message using NTLM2 Session Security Note: [MS-NLMP] Section 3.4.4 The message signature for NTLM with extended session security is a 16-byte value that contains the following components, as described by the NTLMSSP_MESSAGE_SIGNATURE structure: - A 4-byte version-number value that is set to 1 - The first eight bytes of the message's HMAC_MD5 - The 4-byte sequence number (SeqNum) :param message: The message to be signed :return: The signature for supplied message
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/security.py#L260-L288
null
class _Ntlm2Session(object): """ _ _ _____ _ __ __ ___ | \| |_ _| | | \/ | |_ ) SESSION SECURITY | .` | | | | |__| |\/| | / / Windows NT4 SP4 and later |_|\_| |_| |____|_| |_| /___| This is a newer scheme which can be used with both NTLMv1 and NTLMv2 Authentication. """ client_signing = b"session key to client-to-server signing key magic constant\0" client_sealing = b"session key to client-to-server sealing key magic constant\0" server_signing = b"session key to server-to-client signing key magic constant\0" server_sealing = b"session key to server-to-client sealing key magic constant\0" """ """ def __init__(self, flags, session_key, mode): self.key_exchange = True self.outgoing_sequence = 0 self.incoming_sequence = 0 session_key = _Ntlm2Session._weaken_key(flags, session_key) #logger.debug("Session Key after Weakening: %s", AsHex(session_key)) client_signing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.client_signing) server_signing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.server_signing) client_sealing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.client_sealing) server_sealing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.server_sealing) if mode=='client': self.outgoing_signing_key = client_signing_key self.incoming_signing_key = server_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(client_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(server_arc4, mode=None, backend=default_backend()).decryptor() elif mode=='server': self.outgoing_signing_key = server_signing_key self.incoming_signing_key = client_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(server_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(client_arc4, mode=None, backend=default_backend()).decryptor() #logger.debug("Client Signing Key: %s", AsHex(client_signing_key)) #logger.debug("Server Signing Key: %s", AsHex(server_signing_key)) #logger.debug("Client Sealing Key: %s", AsHex(client_sealing_key)) #logger.debug("Server Sealing Key: %s", AsHex(server_sealing_key)) @staticmethod def _generate_key(material): md5 = hashlib.new('md5') md5.update(material) return md5.digest() @staticmethod def _weaken_key(flags, key): """ NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under NTLM2. In this case, the master key is used directly in the generation of subkeys (with no weakening performed). :param flags: The negotiated NTLM flags :return: The 16-byte key to be used to sign messages """ if flags & NegotiateFlag.NTLMSSP_KEY_128: return key if flags & NegotiateFlag.NTLMSSP_NEGOTIATE_56: return key[:7] else: return key[:5] def verify(self, message, signature): """ Verified the signature attached to the supplied message using NTLM2 Session Security :param message: The message whose signature will verified :return: True if the signature is valid, otherwise False """ # Parse the signature header mac = _Ntlm2MessageSignature() mac.from_string(signature) # validate the sequence if mac['sequence'] != self.incoming_sequence: raise Exception("The message was not received in the correct sequence.") # extract the supplied checksum checksum = struct.pack('<q', mac['checksum']) if self.key_exchange: checksum = self.incoming_seal.update(checksum) # calculate the expected checksum for the message hmac_context = hmac.new(self.incoming_signing_key) hmac_context.update(struct.pack('<i', self.incoming_sequence) + message) expected_checksum = hmac_context.digest()[:8] # validate the supplied checksum is correct if checksum != expected_checksum: raise Exception("The message has been altered") #logger.debug("Verify Sequence Number: %s", AsHex(self.outgoing_sequence)) self.incoming_sequence += 1 def encrypt(self, message): """ Encrypts the supplied message using NTLM2 Session Security :param message: The message to be encrypted :return: The signed and encrypted message """ return self.outgoing_seal.update(message) def decrypt(self, cipher_text): """ Decrypts the supplied message using NTLM2 Session Security :param message: The ciphertext to be decrypted :return: The original plaintext """ return self.incoming_seal.update(cipher_text)
ianclegg/ntlmlib
ntlmlib/security.py
_Ntlm2Session.verify
python
def verify(self, message, signature): # Parse the signature header mac = _Ntlm2MessageSignature() mac.from_string(signature) # validate the sequence if mac['sequence'] != self.incoming_sequence: raise Exception("The message was not received in the correct sequence.") # extract the supplied checksum checksum = struct.pack('<q', mac['checksum']) if self.key_exchange: checksum = self.incoming_seal.update(checksum) # calculate the expected checksum for the message hmac_context = hmac.new(self.incoming_signing_key) hmac_context.update(struct.pack('<i', self.incoming_sequence) + message) expected_checksum = hmac_context.digest()[:8] # validate the supplied checksum is correct if checksum != expected_checksum: raise Exception("The message has been altered") #logger.debug("Verify Sequence Number: %s", AsHex(self.outgoing_sequence)) self.incoming_sequence += 1
Verified the signature attached to the supplied message using NTLM2 Session Security :param message: The message whose signature will verified :return: True if the signature is valid, otherwise False
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/security.py#L290-L319
[ "def from_string(self, data):\n self.rawData = data\n for field in self.common_header + self.structure:\n if self.debug:\n print(\"from_string( %s | %s | %r )\" % (field[0], field[1], data))\n size = self.calc_unpack_size(field[1], data, field[0])\n if self.debug:\n print(\" size = %d\" % size)\n data_class_or_code = str\n if len(field) > 2:\n data_class_or_code = field[2]\n try:\n self[field[0]] = self.unpack(field[1], data[:size], data_class_or_code=data_class_or_code,\n field=field[0])\n except Exception as e:\n e.args += (\"When unpacking field '%s | %s | %r[:%d]'\" % (field[0], field[1], data, size),)\n raise\n\n size = self.calcPackSize(field[1], self[field[0]], field[0])\n if self.alignment and size % self.alignment:\n size += self.alignment - (size % self.alignment)\n data = data[size:]\n\n return self\n" ]
class _Ntlm2Session(object): """ _ _ _____ _ __ __ ___ | \| |_ _| | | \/ | |_ ) SESSION SECURITY | .` | | | | |__| |\/| | / / Windows NT4 SP4 and later |_|\_| |_| |____|_| |_| /___| This is a newer scheme which can be used with both NTLMv1 and NTLMv2 Authentication. """ client_signing = b"session key to client-to-server signing key magic constant\0" client_sealing = b"session key to client-to-server sealing key magic constant\0" server_signing = b"session key to server-to-client signing key magic constant\0" server_sealing = b"session key to server-to-client sealing key magic constant\0" """ """ def __init__(self, flags, session_key, mode): self.key_exchange = True self.outgoing_sequence = 0 self.incoming_sequence = 0 session_key = _Ntlm2Session._weaken_key(flags, session_key) #logger.debug("Session Key after Weakening: %s", AsHex(session_key)) client_signing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.client_signing) server_signing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.server_signing) client_sealing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.client_sealing) server_sealing_key = _Ntlm2Session._generate_key(session_key + _Ntlm2Session.server_sealing) if mode=='client': self.outgoing_signing_key = client_signing_key self.incoming_signing_key = server_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(client_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(server_arc4, mode=None, backend=default_backend()).decryptor() elif mode=='server': self.outgoing_signing_key = server_signing_key self.incoming_signing_key = client_signing_key client_arc4 = algorithms.ARC4(client_sealing_key) server_arc4 = algorithms.ARC4(server_sealing_key) self.outgoing_seal = Cipher(server_arc4, mode=None, backend=default_backend()).encryptor() self.incoming_seal = Cipher(client_arc4, mode=None, backend=default_backend()).decryptor() #logger.debug("Client Signing Key: %s", AsHex(client_signing_key)) #logger.debug("Server Signing Key: %s", AsHex(server_signing_key)) #logger.debug("Client Sealing Key: %s", AsHex(client_sealing_key)) #logger.debug("Server Sealing Key: %s", AsHex(server_sealing_key)) @staticmethod def _generate_key(material): md5 = hashlib.new('md5') md5.update(material) return md5.digest() @staticmethod def _weaken_key(flags, key): """ NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under NTLM2. In this case, the master key is used directly in the generation of subkeys (with no weakening performed). :param flags: The negotiated NTLM flags :return: The 16-byte key to be used to sign messages """ if flags & NegotiateFlag.NTLMSSP_KEY_128: return key if flags & NegotiateFlag.NTLMSSP_NEGOTIATE_56: return key[:7] else: return key[:5] def sign(self, message): """ Generates a signature for the supplied message using NTLM2 Session Security Note: [MS-NLMP] Section 3.4.4 The message signature for NTLM with extended session security is a 16-byte value that contains the following components, as described by the NTLMSSP_MESSAGE_SIGNATURE structure: - A 4-byte version-number value that is set to 1 - The first eight bytes of the message's HMAC_MD5 - The 4-byte sequence number (SeqNum) :param message: The message to be signed :return: The signature for supplied message """ hmac_context = hmac.new(self.outgoing_signing_key) hmac_context.update(struct.pack('<i', self.outgoing_sequence) + message) # If a key exchange key is negotiated the first 8 bytes of the HMAC MD5 are encrypted with RC4 if self.key_exchange: checksum = self.outgoing_seal.update(hmac_context.digest()[:8]) else: checksum = hmac_context.digest()[:8] mac = _Ntlm2MessageSignature() mac['checksum'] = struct.unpack('<q', checksum)[0] mac['sequence'] = self.outgoing_sequence #logger.debug("Signing Sequence Number: %s", str(self.outgoing_sequence)) # Increment the sequence number after signing each message self.outgoing_sequence += 1 return str(mac) def encrypt(self, message): """ Encrypts the supplied message using NTLM2 Session Security :param message: The message to be encrypted :return: The signed and encrypted message """ return self.outgoing_seal.update(message) def decrypt(self, cipher_text): """ Decrypts the supplied message using NTLM2 Session Security :param message: The ciphertext to be decrypted :return: The original plaintext """ return self.incoming_seal.update(cipher_text)
ianclegg/ntlmlib
ntlmlib/security.py
Ntlm2Sealing.wrap
python
def wrap(self, message): cipher_text = _Ntlm2Session.encrypt(self, message) signature = _Ntlm2Session.sign(self, message) return cipher_text, signature
NTM GSSwrap() :param message: The message to be encrypted :return: A Tuple containing the signature and the encrypted messaging
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/security.py#L356-L364
[ "def sign(self, message):\n \"\"\"\n Generates a signature for the supplied message using NTLM2 Session Security\n Note: [MS-NLMP] Section 3.4.4\n The message signature for NTLM with extended session security is a 16-byte value that contains the following\n components, as described by the NTLMSSP_MESSAGE_SIGNATURE structure:\n - A 4-byte version-number value that is set to 1\n - The first eight bytes of the message's HMAC_MD5\n - The 4-byte sequence number (SeqNum)\n :param message: The message to be signed\n :return: The signature for supplied message\n \"\"\"\n hmac_context = hmac.new(self.outgoing_signing_key)\n hmac_context.update(struct.pack('<i', self.outgoing_sequence) + message)\n\n # If a key exchange key is negotiated the first 8 bytes of the HMAC MD5 are encrypted with RC4\n if self.key_exchange:\n checksum = self.outgoing_seal.update(hmac_context.digest()[:8])\n else:\n checksum = hmac_context.digest()[:8]\n\n mac = _Ntlm2MessageSignature()\n mac['checksum'] = struct.unpack('<q', checksum)[0]\n mac['sequence'] = self.outgoing_sequence\n #logger.debug(\"Signing Sequence Number: %s\", str(self.outgoing_sequence))\n\n # Increment the sequence number after signing each message\n self.outgoing_sequence += 1\n return str(mac)\n", "def encrypt(self, message):\n \"\"\"\n Encrypts the supplied message using NTLM2 Session Security\n :param message: The message to be encrypted\n :return: The signed and encrypted message\n \"\"\"\n return self.outgoing_seal.update(message)\n" ]
class Ntlm2Sealing(_Ntlm2Session): """ """ def __init__(self, flags, session_key, mode='client'): _Ntlm2Session.__init__(self, flags, session_key, mode) def unwrap(self, message, signature): """ NTLM GSSUnwrap() :param message: The message to be decrypted :return: The decrypted message """ plain_text = _Ntlm2Session.decrypt(self, message) _Ntlm2Session.verify(self, plain_text, signature) return plain_text
ianclegg/ntlmlib
ntlmlib/security.py
Ntlm2Sealing.unwrap
python
def unwrap(self, message, signature): plain_text = _Ntlm2Session.decrypt(self, message) _Ntlm2Session.verify(self, plain_text, signature) return plain_text
NTLM GSSUnwrap() :param message: The message to be decrypted :return: The decrypted message
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/security.py#L366-L374
[ "def verify(self, message, signature):\n \"\"\"\n Verified the signature attached to the supplied message using NTLM2 Session Security\n :param message: The message whose signature will verified\n :return: True if the signature is valid, otherwise False\n \"\"\"\n # Parse the signature header\n mac = _Ntlm2MessageSignature()\n mac.from_string(signature)\n\n # validate the sequence\n if mac['sequence'] != self.incoming_sequence:\n raise Exception(\"The message was not received in the correct sequence.\")\n\n # extract the supplied checksum\n checksum = struct.pack('<q', mac['checksum'])\n if self.key_exchange:\n checksum = self.incoming_seal.update(checksum)\n\n # calculate the expected checksum for the message\n hmac_context = hmac.new(self.incoming_signing_key)\n hmac_context.update(struct.pack('<i', self.incoming_sequence) + message)\n expected_checksum = hmac_context.digest()[:8]\n\n # validate the supplied checksum is correct\n if checksum != expected_checksum:\n raise Exception(\"The message has been altered\")\n\n #logger.debug(\"Verify Sequence Number: %s\", AsHex(self.outgoing_sequence))\n self.incoming_sequence += 1\n", "def decrypt(self, cipher_text):\n \"\"\"\n Decrypts the supplied message using NTLM2 Session Security\n :param message: The ciphertext to be decrypted\n :return: The original plaintext\n \"\"\"\n return self.incoming_seal.update(cipher_text)\n" ]
class Ntlm2Sealing(_Ntlm2Session): """ """ def __init__(self, flags, session_key, mode='client'): _Ntlm2Session.__init__(self, flags, session_key, mode) def wrap(self, message): """ NTM GSSwrap() :param message: The message to be encrypted :return: A Tuple containing the signature and the encrypted messaging """ cipher_text = _Ntlm2Session.encrypt(self, message) signature = _Ntlm2Session.sign(self, message) return cipher_text, signature
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication.get_lm_response
python
def get_lm_response(self, flags, challenge): # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key
Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L127-L145
[ "def _get_lm_response(password, challenge):\n lm_hash = PasswordAuthentication.lmowfv1(password)\n response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge)\n response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge)\n response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge)\n\n # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes\n key_padding = b'\\0' * 8\n key = lm_hash[:8] + key_padding\n return response, key\n", "def get_ntlmv1_response(password, challenge):\n \"\"\"\n Generate the Unicode MD4 hash for the password associated with these credentials.\n \"\"\"\n ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le'))\n response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge)\n response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge)\n response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge)\n\n # The NTLMv1 session key is simply the MD4 hash of the ntlm hash\n session_hash = hashlib.new('md4')\n session_hash.update(ntlm_hash)\n return response, session_hash.digest()\n", "def get_lmv2_response(domain, username, password, server_challenge, client_challenge):\n \"\"\"\n Computes an appropriate LMv2 response based on the supplied arguments\n The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash\n concatenated with the 8 byte client client_challenge\n \"\"\"\n ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le'))\n hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend())\n hmac_context.update(server_challenge)\n hmac_context.update(client_challenge)\n lmv2_hash = hmac_context.finalize()\n\n # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash\n session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend())\n session_key.update(lmv2_hash)\n\n return lmv2_hash + client_challenge, session_key.finalize()\n" ]
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication.get_ntlm_response
python
def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info
Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L147-L191
[ "def _get_ntlm_timestamp():\n # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the\n # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC).\n # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding\n # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds.\n return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000))\n", "def get_ntlmv1_response(password, challenge):\n \"\"\"\n Generate the Unicode MD4 hash for the password associated with these credentials.\n \"\"\"\n ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le'))\n response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge)\n response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge)\n response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge)\n\n # The NTLMv1 session key is simply the MD4 hash of the ntlm hash\n session_hash = hashlib.new('md4')\n session_hash.update(ntlm_hash)\n return response, session_hash.digest()\n", "def get_ntlm2_response(password, server_challenge, client_challenge):\n \"\"\"\n Generate the Unicode MD4 hash for the password associated with these credentials.\n \"\"\"\n md5 = hashlib.new('md5')\n md5.update(server_challenge + client_challenge)\n ntlm2_session_hash = md5.digest()[:8]\n ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le'))\n response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash)\n response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash)\n response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash)\n\n session_hash = hashlib.new('md4')\n session_hash.update(ntlm_hash)\n hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend())\n hmac_context.update(server_challenge + client_challenge)\n return response, hmac_context.finalize()\n", "def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info):\n \"\"\"\n [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol\n 3.3.2 NTLM v2 Authentication\n\n Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse()\n implementation the protocol documentation.\n Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for\n historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS\n structure called target_info. The reserved constants below are defined in the documentation\n\n :param response_key: The return value from NTOWF()\n :param server_challenge: The 8-byte challenge message generated by the server\n :param client_challenge: The 8-byte challenge message generated by the client\n :param timestamp: The 8-byte little-endian time in GMT\n :param target_info: The AttributeValuePairs structure to be returned to the server\n :return: NTLMv2 Response\n \"\"\"\n lo_response_version = b'\\x01'\n hi_response_version = b'\\x01'\n reserved_dword = b'\\x00' * 4\n reserved_bytes = b'\\x00' * 6\n\n response_key = PasswordAuthentication.ntowfv2(domain, user, password)\n proof_material = lo_response_version\n proof_material += hi_response_version\n proof_material += reserved_bytes\n proof_material += timestamp\n proof_material += client_challenge\n proof_material += reserved_dword\n proof_material += target_info.get_data()\n proof_material += reserved_dword\n proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material)\n\n # The master session key derivation\n session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend())\n session_key.update(proof)\n session_master_key = session_key.finalize()\n return proof + proof_material, session_master_key, target_info\n" ]
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication._expand_des_key
python
def _expand_des_key(key): key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s
Expand the key from a 7-byte password key into a 8-byte DES key
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L194-L208
null
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication.get_ntlmv1_response
python
def get_ntlmv1_response(password, challenge): ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest()
Generate the Unicode MD4 hash for the password associated with these credentials.
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L237-L249
[ "def _encrypt_des_block(key, msg):\n expanded = PasswordAuthentication._expand_des_key(key)\n cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor()\n return cipher.update(msg) + cipher.finalize()\n", "def ntowfv1(password):\n md4 = hashlib.new('md4')\n md4.update(password)\n return md4.digest()\n" ]
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication.get_ntlm2_response
python
def get_ntlm2_response(password, server_challenge, client_challenge): md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize()
Generate the Unicode MD4 hash for the password associated with these credentials.
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L252-L268
[ "def _encrypt_des_block(key, msg):\n expanded = PasswordAuthentication._expand_des_key(key)\n cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor()\n return cipher.update(msg) + cipher.finalize()\n", "def ntowfv1(password):\n md4 = hashlib.new('md4')\n md4.update(password)\n return md4.digest()\n" ]
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication.ntowfv2
python
def ntowfv2(domain, user, password): md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize()
NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L285-L300
null
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication._compute_response
python
def _compute_response(response_key, server_challenge, client_challenge): hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize()
ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L303-L316
null
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication.get_lmv2_response
python
def get_lmv2_response(domain, username, password, server_challenge, client_challenge): ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize()
Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L319-L335
[ "def ntowfv2(domain, user, password):\n \"\"\"\n NTOWFv2() Implementation\n [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol\n 3.3.2 NTLM v2 Authentication\n :param domain: The windows domain name\n :param user: The windows username\n :param password: The users password\n :return: Hash Data\n \"\"\"\n md4 = hashlib.new('md4')\n md4.update(password)\n hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend())\n hmac_context.update(user.upper().encode('utf-16le'))\n hmac_context.update(domain.encode('utf-16le'))\n return hmac_context.finalize()\n" ]
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod @staticmethod def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response """ lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
ianclegg/ntlmlib
ntlmlib/authentication.py
PasswordAuthentication.get_ntlmv2_response
python
def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += timestamp proof_material += client_challenge proof_material += reserved_dword proof_material += target_info.get_data() proof_material += reserved_dword proof = PasswordAuthentication._compute_response(response_key, server_challenge, proof_material) # The master session key derivation session_key = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) session_key.update(proof) session_master_key = session_key.finalize() return proof + proof_material, session_master_key, target_info
[MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refers to a variable called ServerName, this is for historical reasons and is misleading. ServerName refers to the bytes that compose the AV_PAIRS structure called target_info. The reserved constants below are defined in the documentation :param response_key: The return value from NTOWF() :param server_challenge: The 8-byte challenge message generated by the server :param client_challenge: The 8-byte challenge message generated by the client :param timestamp: The 8-byte little-endian time in GMT :param target_info: The AttributeValuePairs structure to be returned to the server :return: NTLMv2 Response
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/authentication.py#L338-L376
[ "def ntowfv2(domain, user, password):\n \"\"\"\n NTOWFv2() Implementation\n [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol\n 3.3.2 NTLM v2 Authentication\n :param domain: The windows domain name\n :param user: The windows username\n :param password: The users password\n :return: Hash Data\n \"\"\"\n md4 = hashlib.new('md4')\n md4.update(password)\n hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend())\n hmac_context.update(user.upper().encode('utf-16le'))\n hmac_context.update(domain.encode('utf-16le'))\n return hmac_context.finalize()\n", "def _compute_response(response_key, server_challenge, client_challenge):\n \"\"\"\n ComputeResponse() has been refactored slightly to reduce its complexity and improve\n readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been\n removed. Users should not call this method directly, they should rely on get_lmv2_response\n and get_ntlmv2_response depending on the negotiated flags.\n\n [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol\n 3.3.2 NTLM v2 Authentication\n \"\"\"\n hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend())\n hmac_context.update(server_challenge)\n hmac_context.update(client_challenge)\n return hmac_context.finalize()\n", "def get_data(self):\n if TargetInfo.NTLMSSP_AV_EOL in self.fields:\n del self.fields[TargetInfo.NTLMSSP_AV_EOL]\n\n data = b''\n for i in self.fields.keys():\n data += struct.pack('<HH', i, self[i][0])\n data += self[i][1]\n\n # end with a NTLMSSP_AV_EOL\n data += struct.pack('<HH', TargetInfo.NTLMSSP_AV_EOL, 0)\n return data\n" ]
class PasswordAuthentication(object): """ Initializes the PasswordAuthentication with the supplied domain, username and password. """ known_des_input = b'KGS!@#$%' def __init__(self, domain, username, password, **kwargs): """ Initializes the PasswordAuthentication with the supplied domain, username and password. :param domain: The windows domain name :param user: The windows username :param password: The users password :param: kwargs: A optional dictionary which can be used to configure Compatibility Flags ------------------- disable_mic - Windows Vista and later support the inclusion of a MIC (Message Integrity Code) during authentication. MIC codes are optional during authentication, but offer obvious security benefits. Setting this flag to 'True' will disable then generation of MIC codes; emulating the behavior of Windows XP and earlier. Default and recommended value is 'False' disable_timestamp - When 'True' the timestamp in the MsvAvTimestamp pair (if present) is used the NTLMv2 computation. Setting the flag to 'False' emulates Windows XP/2003 and earlier clients which ignore the MsvAvTimestamp. Default and recommended value is 'True' disable_only_128 - Windows NT4 SP4 and later support 128bit session keys. If session security is negotiated with anything less the protocol may have been compromised. Setting this flag to 'True' will enable support for 56bit and 40bit keys by disabling exceptions which are normally raised if 128bit encryption is not negotiated. The default and recommended value is 'False' Application Supplied Data ------------------------- spn_target - Service principal name (SPN) of the service to which the client wishes to authenticate. Default value is 'None' It is only necessary to include a Client Supplied TargetName when explicitly required by the server application. SPN Target Name is only supported on Windows Vista or later. channel_bindings - A byte string representing the 'gss_channel_bindings_struct' which will be hashed and sent during authentication. If the value is 'None' channel bindings will not be sent. Default value is 'None' It is only necessary to include Channel Bindings if the server application explicitly requires it. Channel Bindings are only supported on Windows Server 2008 R2 and later. compatibility - Lan Manager Compatibility Level to use On Windows Clients the level is set by an 'Administrator' in HKLM\SYSTEM\CurrentControlSet\Control\Lsa\LmCompatibilityLevel 0 : Use LM and NTLM authentication, but never use NTLMv2 session security. 1 : Use LM and NTLM authentication, but use NTLMv2 session security if possible 2 : Use only NTLM authentication, but use NTLMv2 session security if possible 3 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 4 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible 5 : Use only NTLMv2 authentication, but use NTLMv2 session security if possible Note: Levels 3 to 5 are identical in terms of client behaviour, they only differ with respect to Domain Controller behaviour which is not applicable here NTLMv1 and NTLM2 Signing and Sealing is only available in Windows NT 4.0 SP4 and later """ self._domain = domain self._username = username self._password = password self._challenge = kwargs.get('challenge', None) self._lm_compatibility = kwargs.get('compatibility', 3) if (self._lm_compatibility < 0) or (self._lm_compatibility > 5): raise Exception('Unknown Lan Manager Compatibility Level') # Initialise a random default 8 byte NTLM client challenge self._client_challenge = os.urandom(8) # NTLM participants can include additional data in the TargetInfo (AV_PAIRS) to prevent MiTM and replay attacks self._av_timestamp = kwargs.get('timestamp', True) self._av_channel_bindings = kwargs.get('channel_bindings', None) def get_domain(self): """ :return: The windows domain name """ return self._domain def get_username(self): """ :return: The windows username """ return self._username def get_password(self): """ :return: The password for the user if it is available """ return self._password def get_compatibility_level(self): """ :return: The Lan Manager Compatibility Level """ return self._lm_compatibility def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None elif 0 <= self._lm_compatibility <= 1: response, key = PasswordAuthentication._get_lm_response(self._password, challenge) elif self._lm_compatibility == 2: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password, challenge, self._client_challenge) return response, key def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :return: A tuple containing the 24 byte NTLM Hash, Session Key and TargetInfo """ # TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD NOT send # the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlm2_response(self._password, challenge, self._client_challenge) elif 0 <= self._lm_compatibility < 3: response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge) else: # We should use the timestamp included in TargetInfo, if no timestamp is set we generate one and add it to # the outgoing TargetInfo. If the timestamp is set, we should also set the MIC flag if target_info is None: target_info = TargetInfo() if target_info[TargetInfo.NTLMSSP_AV_TIME] is None: timestamp = PasswordAuthentication._get_ntlm_timestamp() else: # TODO: If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present, # TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and channel_binding is not None: # target_info[TargetInfo.NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding response, key, target_info = PasswordAuthentication.get_ntlmv2_response( self._domain, self._username, self._password.encode('utf-16le'), challenge, self._client_challenge, timestamp, target_info) return response, key, target_info @staticmethod def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> 3) & 0x1f)) << 1) s += struct.pack("B", ((byte[2] & 0x07) << 4 | ((byte[3] >> 4) & 0x0f)) << 1) s += struct.pack("B", ((byte[3] & 0x0f) << 3 | ((byte[4] >> 5) & 0x07)) << 1) s += struct.pack("B", ((byte[4] & 0x1f) << 2 | ((byte[5] >> 6) & 0x03)) << 1) s += struct.pack("B", ((byte[5] & 0x3f) << 1 | ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s @staticmethod def _encrypt_des_block(key, msg): expanded = PasswordAuthentication._expand_des_key(key) cipher = Cipher(algorithms.TripleDES(expanded), modes.ECB(), backend=default_backend()).encryptor() return cipher.update(msg) + cipher.finalize() @staticmethod def _get_ntlm_timestamp(): # The NTLM timestamp is a 64-bit unsigned integer that contains the current system time, represented as the # number of 100 nanosecond ticks elapsed since midnight of January 1, 1601 (UTC). # We must calculate this value from the Unix Epoch (seconds since Thursday, 1 January 1970 UTC) by adding # 116444736000000000 to rebase to January 1, 1601 then multiply by 10000000 to convert to 100 nanoseconds. return struct.pack('<q', (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)) @staticmethod def _get_lm_response(password, challenge): lm_hash = PasswordAuthentication.lmowfv1(password) response = PasswordAuthentication._encrypt_des_block(lm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(lm_hash[14:], challenge) # The lm user session key is the first 8 bytes of the hash concatenated with 8 zero bytes key_padding = b'\0' * 8 key = lm_hash[:8] + key_padding return response, key @staticmethod def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], challenge) # The NTLMv1 session key is simply the MD4 hash of the ntlm hash session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) return response, session_hash.digest() @staticmethod def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], ntlm2_session_hash) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[14:], ntlm2_session_hash) session_hash = hashlib.new('md4') session_hash.update(ntlm_hash) hmac_context = hmac.HMAC(session_hash.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge + client_challenge) return response, hmac_context.finalize() @staticmethod def lmowfv1(password): # verify OEM codepage is always ascii password = password.encode('ascii').upper() lmhash = PasswordAuthentication._encrypt_des_block(password[:7], PasswordAuthentication.known_des_input) lmhash += PasswordAuthentication._encrypt_des_block(password[7:14], PasswordAuthentication.known_des_input) return lmhash @staticmethod def ntowfv1(password): md4 = hashlib.new('md4') md4.update(password) return md4.digest() @staticmethod def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize() @staticmethod def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response depending on the negotiated flags. [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication """ hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize() @staticmethod def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context.finalize() # The LMv2 master user session key is a HMAC MD5 of the NTLMv2 and LMv2 hash session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) session_key.update(lmv2_hash) return lmv2_hash + client_challenge, session_key.finalize() @staticmethod
ianclegg/ntlmlib
ntlmlib/context.py
_mic_required
python
def _mic_required(target_info): if target_info is not None and target_info[TargetInfo.NTLMSSP_AV_FLAGS] is not None: flags = struct.unpack('<I', target_info[TargetInfo.NTLMSSP_AV_FLAGS][1])[0] return bool(flags & 0x00000002)
Checks the MsvAvFlags field of the supplied TargetInfo structure to determine in the MIC flags is set :param target_info: The TargetInfo structure to check :return: a boolean value indicating that the MIC flag is set
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/context.py#L223-L231
null
""" (c) 2015, Ian Clegg <ian.clegg@sourcewarp.com> ntlmlib is 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. """ import os import struct import logging from socket import gethostname from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, hmac from cryptography.hazmat.primitives.ciphers import Cipher, algorithms from ntlmlib.helpers import AsHex from ntlmlib.messages import Negotiate from ntlmlib.messages import Challenge from ntlmlib.messages import ChallengeResponse from ntlmlib.messages import TargetInfo from ntlmlib.security import Ntlm2Sealing from ntlmlib.constants import NegotiateFlag logger = logging.getLogger(__name__) """ """ class NtlmContext(object): """ For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. """ def __init__(self, authenticator, session_security='none', **kwargs): if session_security not in ('none', 'sign', 'encrypt'): raise Exception("session_security must be none, sign or encrypt") # Initialise a random default 8 byte NTLM client challenge self._os_version = kwargs.get('version', (6, 6, 0)) # Initialise a random default 8 byte NTLM client challenge self._hostname = kwargs.get('hostname', gethostname()) # TODO, should accept a list of possible in order of preference # these should probably be 'integrity' and 'confidentiality' # encrypt, sign, none would not raise an error # TODO, we should set the negotiate flags based on the lm level :-s # Note, this still works with 9x and N4.0 though self.flags = NegotiateFlag.NTLMSSP_TARGET |\ NegotiateFlag.NTLMSSP_TARGET_INFO |\ NegotiateFlag.NTLMSSP_KEY_128 if session_security == 'sign': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_NTLM2_KEY if session_security == 'encrypt': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_SEAL |\ NegotiateFlag.NTLMSSP_NTLM2_KEY self._wrapper = None self._session_key = None self._authenticator = authenticator self._session_security = session_security self.is_established = False def is_established(self): return self.is_established def initialize_security_context(self): """ Idiomatic Python implementation of initialize_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Generate the NTLM Negotiate Request negotiate_token = self._negotiate(self.flags) challenge_token = yield negotiate_token # Generate the Authenticate Response authenticate_token = self._challenge_response(negotiate_token, challenge_token) yield authenticate_token def aquire_security_context(self): """ Idiomatic Python implementation of aquire_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Accept the negotiate token negotiate_token = (yield) # Generate the Challenge token authenticate_token = yield self._challenge(negotiate_token) # check the authenticate token #authenticate_token raise Exception("aquire_security_context is not yet implemented") def wrap_message(self, message): """ Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the optionally encrypted message """ if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.wrap(message) def unwrap_message(self, message, signature): """ Verifies the supplied signature against the message and decrypts the message if 'confidentiality' was negotiated. A SignatureException is raised if the signature cannot be parsed or the version is unsupported A SequenceException is raised if the sequence number in the signature is incorrect A ChecksumException is raised if the in the signature checksum is invalid :return: The decrypted message """ if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.unwrap(message, signature) def _negotiate(self, flags): # returns the response return Negotiate(flags, self._authenticator.get_domain(), self._hostname).get_data() def _challenge_response(self, negotiate_token, challenge_token): challenge = Challenge() challenge.from_string(challenge_token) flags = challenge['flags'] nonce = challenge['challenge'] challenge_target = challenge['target_info_fields'] # Compute the ntlm response; this depends on an interplay between the ntlm challenge flags and the settings # used to construct the 'authenticator' object ntlm_response, session_key, target_info = self._authenticator.get_ntlm_response(flags, nonce, challenge_target) # 3.1.5.2.1 Client Receives a CHALLENGE_MESSAGE # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD # NOT send the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen #### TODO Fix lm_response session key if challenge_target is None and target_info is None: lm_response = '' else: lm_response, fix_me = self._authenticator.get_lm_response(flags, nonce) # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If the we negotiated key exchange, generate a new new master key for the session, this is RC4-encrypted # with the previously selected session key. # "This capability SHOULD be used because it improves security for message integrity or confidentiality" if flags & NegotiateFlag.NTLMSSP_KEY_EXCHANGE: cipher = Cipher(algorithms.ARC4(session_key), mode=None, backend=default_backend()).encryptor() session_key = os.urandom(16) exported_session_key = cipher.update(session_key) else: exported_session_key = session_key # Ensure the negotiated flags guarantee at least the minimum level of session security required by the # client when the context was constructed if 'encrypt' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SEAL: raise Exception("failed to negotiate session encryption") if 'sign' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SIGN: raise Exception("failed to negotiate session encryption") authenticate = ChallengeResponse(flags, lm_response, ntlm_response, self._authenticator.get_domain(), self._authenticator.get_username(), exported_session_key) # If the authenticate response has the MIC flag set, we must calculate and set the mic field the 'authenticator' # object determines when mic code generation is required and sets this flag if _mic_required(target_info): _add_mic(authenticate, session_key, negotiate_token, challenge_token) # If session security was negotiated we should construct an appropriate object to perform the subsequent # message wrapping and unwrapping # We need a factory which will construct the correct wrapper based on the flags, it needs to support # NTLM1 and NTLM2 Session Security. This is tricky, because it needs the correct key based on flags # for NTLM1, 'Negotiate Lan Manager Key' determines if we need a User Session Key or Lan Manager Session Key # this needs to be done in advance by whatever computes the master key and key exchange key # #logger.debug("Negotiated Session Key: %s", AsHex(session_key)) if flags & NegotiateFlag.NTLMSSP_SEAL: self._wrapper = Ntlm2Sealing(flags, session_key, 'client') elif flags & NegotiateFlag.NTLMSSP_SIGN: self._wrapper = Ntlm2Signing(flags, session_key) # TODO: Check the returned flags are set correctly #if flags & NegotiateFlag.NTLMSSP_VERSION: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_VERSION #if flags & NegotiateFlag.NTLMSSP_NTLM_KEY: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_NTLM_KEY self.is_established = True self.flags = flags return authenticate.get_data() def _add_mic(authenticate, session_key, negotiate_token, challenge_token): """ :param authenticate: :param session_key: :param negotiate_token: :param challenge_token: :return: """ # before computing the MIC, the version field must be preset and the MIC # field must be zeroed out of the authenticate message. authenticate['mic'] = '\x00' * 16 authenticate['version'] = '\x06\x01\xb1\x1d\x00\x00\x00\x0f' authenticate_token = authenticate.get_data() # compute the MIC mic = hmac.HMAC(session_key, hashes.MD5(), backend=default_backend()) mic.update(negotiate_token) mic.update(challenge_token) mic.update(authenticate_token) # set the MIC authenticate['mic'] = mic.finalize()
ianclegg/ntlmlib
ntlmlib/context.py
NtlmContext.initialize_security_context
python
def initialize_security_context(self): # Generate the NTLM Negotiate Request negotiate_token = self._negotiate(self.flags) challenge_token = yield negotiate_token # Generate the Authenticate Response authenticate_token = self._challenge_response(negotiate_token, challenge_token) yield authenticate_token
Idiomatic Python implementation of initialize_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/context.py#L84-L96
[ "def _negotiate(self, flags):\n # returns the response\n return Negotiate(flags, self._authenticator.get_domain(), self._hostname).get_data()\n", "def _challenge_response(self, negotiate_token, challenge_token):\n challenge = Challenge()\n challenge.from_string(challenge_token)\n flags = challenge['flags']\n nonce = challenge['challenge']\n challenge_target = challenge['target_info_fields']\n\n # Compute the ntlm response; this depends on an interplay between the ntlm challenge flags and the settings\n # used to construct the 'authenticator' object\n ntlm_response, session_key, target_info = self._authenticator.get_ntlm_response(flags, nonce, challenge_target)\n\n # 3.1.5.2.1 Client Receives a CHALLENGE_MESSAGE\n # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46)\n # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD\n # NOT send the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen\n\n #### TODO Fix lm_response session key\n if challenge_target is None and target_info is None:\n lm_response = ''\n else:\n lm_response, fix_me = self._authenticator.get_lm_response(flags, nonce)\n\n # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46)\n # If the we negotiated key exchange, generate a new new master key for the session, this is RC4-encrypted\n # with the previously selected session key.\n # \"This capability SHOULD be used because it improves security for message integrity or confidentiality\"\n if flags & NegotiateFlag.NTLMSSP_KEY_EXCHANGE:\n cipher = Cipher(algorithms.ARC4(session_key), mode=None, backend=default_backend()).encryptor()\n session_key = os.urandom(16)\n exported_session_key = cipher.update(session_key)\n else:\n exported_session_key = session_key\n\n # Ensure the negotiated flags guarantee at least the minimum level of session security required by the\n # client when the context was constructed\n if 'encrypt' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SEAL:\n raise Exception(\"failed to negotiate session encryption\")\n\n if 'sign' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SIGN:\n raise Exception(\"failed to negotiate session encryption\")\n\n authenticate = ChallengeResponse(flags, lm_response, ntlm_response,\n self._authenticator.get_domain(), self._authenticator.get_username(),\n exported_session_key)\n\n # If the authenticate response has the MIC flag set, we must calculate and set the mic field the 'authenticator'\n # object determines when mic code generation is required and sets this flag\n if _mic_required(target_info):\n _add_mic(authenticate, session_key, negotiate_token, challenge_token)\n\n # If session security was negotiated we should construct an appropriate object to perform the subsequent\n # message wrapping and unwrapping\n\n # We need a factory which will construct the correct wrapper based on the flags, it needs to support\n # NTLM1 and NTLM2 Session Security. This is tricky, because it needs the correct key based on flags\n # for NTLM1, 'Negotiate Lan Manager Key' determines if we need a User Session Key or Lan Manager Session Key\n # this needs to be done in advance by whatever computes the master key and key exchange key\n #\n #logger.debug(\"Negotiated Session Key: %s\", AsHex(session_key))\n if flags & NegotiateFlag.NTLMSSP_SEAL:\n self._wrapper = Ntlm2Sealing(flags, session_key, 'client')\n elif flags & NegotiateFlag.NTLMSSP_SIGN:\n self._wrapper = Ntlm2Signing(flags, session_key)\n\n # TODO: Check the returned flags are set correctly\n #if flags & NegotiateFlag.NTLMSSP_VERSION:\n # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_VERSION\n #if flags & NegotiateFlag.NTLMSSP_NTLM_KEY:\n # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_NTLM_KEY\n\n self.is_established = True\n self.flags = flags\n\n return authenticate.get_data()\n" ]
class NtlmContext(object): """ For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. """ def __init__(self, authenticator, session_security='none', **kwargs): if session_security not in ('none', 'sign', 'encrypt'): raise Exception("session_security must be none, sign or encrypt") # Initialise a random default 8 byte NTLM client challenge self._os_version = kwargs.get('version', (6, 6, 0)) # Initialise a random default 8 byte NTLM client challenge self._hostname = kwargs.get('hostname', gethostname()) # TODO, should accept a list of possible in order of preference # these should probably be 'integrity' and 'confidentiality' # encrypt, sign, none would not raise an error # TODO, we should set the negotiate flags based on the lm level :-s # Note, this still works with 9x and N4.0 though self.flags = NegotiateFlag.NTLMSSP_TARGET |\ NegotiateFlag.NTLMSSP_TARGET_INFO |\ NegotiateFlag.NTLMSSP_KEY_128 if session_security == 'sign': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_NTLM2_KEY if session_security == 'encrypt': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_SEAL |\ NegotiateFlag.NTLMSSP_NTLM2_KEY self._wrapper = None self._session_key = None self._authenticator = authenticator self._session_security = session_security self.is_established = False def is_established(self): return self.is_established def aquire_security_context(self): """ Idiomatic Python implementation of aquire_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Accept the negotiate token negotiate_token = (yield) # Generate the Challenge token authenticate_token = yield self._challenge(negotiate_token) # check the authenticate token #authenticate_token raise Exception("aquire_security_context is not yet implemented") def wrap_message(self, message): """ Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the optionally encrypted message """ if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.wrap(message) def unwrap_message(self, message, signature): """ Verifies the supplied signature against the message and decrypts the message if 'confidentiality' was negotiated. A SignatureException is raised if the signature cannot be parsed or the version is unsupported A SequenceException is raised if the sequence number in the signature is incorrect A ChecksumException is raised if the in the signature checksum is invalid :return: The decrypted message """ if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.unwrap(message, signature) def _negotiate(self, flags): # returns the response return Negotiate(flags, self._authenticator.get_domain(), self._hostname).get_data() def _challenge_response(self, negotiate_token, challenge_token): challenge = Challenge() challenge.from_string(challenge_token) flags = challenge['flags'] nonce = challenge['challenge'] challenge_target = challenge['target_info_fields'] # Compute the ntlm response; this depends on an interplay between the ntlm challenge flags and the settings # used to construct the 'authenticator' object ntlm_response, session_key, target_info = self._authenticator.get_ntlm_response(flags, nonce, challenge_target) # 3.1.5.2.1 Client Receives a CHALLENGE_MESSAGE # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD # NOT send the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen #### TODO Fix lm_response session key if challenge_target is None and target_info is None: lm_response = '' else: lm_response, fix_me = self._authenticator.get_lm_response(flags, nonce) # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If the we negotiated key exchange, generate a new new master key for the session, this is RC4-encrypted # with the previously selected session key. # "This capability SHOULD be used because it improves security for message integrity or confidentiality" if flags & NegotiateFlag.NTLMSSP_KEY_EXCHANGE: cipher = Cipher(algorithms.ARC4(session_key), mode=None, backend=default_backend()).encryptor() session_key = os.urandom(16) exported_session_key = cipher.update(session_key) else: exported_session_key = session_key # Ensure the negotiated flags guarantee at least the minimum level of session security required by the # client when the context was constructed if 'encrypt' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SEAL: raise Exception("failed to negotiate session encryption") if 'sign' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SIGN: raise Exception("failed to negotiate session encryption") authenticate = ChallengeResponse(flags, lm_response, ntlm_response, self._authenticator.get_domain(), self._authenticator.get_username(), exported_session_key) # If the authenticate response has the MIC flag set, we must calculate and set the mic field the 'authenticator' # object determines when mic code generation is required and sets this flag if _mic_required(target_info): _add_mic(authenticate, session_key, negotiate_token, challenge_token) # If session security was negotiated we should construct an appropriate object to perform the subsequent # message wrapping and unwrapping # We need a factory which will construct the correct wrapper based on the flags, it needs to support # NTLM1 and NTLM2 Session Security. This is tricky, because it needs the correct key based on flags # for NTLM1, 'Negotiate Lan Manager Key' determines if we need a User Session Key or Lan Manager Session Key # this needs to be done in advance by whatever computes the master key and key exchange key # #logger.debug("Negotiated Session Key: %s", AsHex(session_key)) if flags & NegotiateFlag.NTLMSSP_SEAL: self._wrapper = Ntlm2Sealing(flags, session_key, 'client') elif flags & NegotiateFlag.NTLMSSP_SIGN: self._wrapper = Ntlm2Signing(flags, session_key) # TODO: Check the returned flags are set correctly #if flags & NegotiateFlag.NTLMSSP_VERSION: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_VERSION #if flags & NegotiateFlag.NTLMSSP_NTLM_KEY: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_NTLM_KEY self.is_established = True self.flags = flags return authenticate.get_data()
ianclegg/ntlmlib
ntlmlib/context.py
NtlmContext.wrap_message
python
def wrap_message(self, message): if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.wrap(message)
Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the optionally encrypted message
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/context.py#L114-L125
null
class NtlmContext(object): """ For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. """ def __init__(self, authenticator, session_security='none', **kwargs): if session_security not in ('none', 'sign', 'encrypt'): raise Exception("session_security must be none, sign or encrypt") # Initialise a random default 8 byte NTLM client challenge self._os_version = kwargs.get('version', (6, 6, 0)) # Initialise a random default 8 byte NTLM client challenge self._hostname = kwargs.get('hostname', gethostname()) # TODO, should accept a list of possible in order of preference # these should probably be 'integrity' and 'confidentiality' # encrypt, sign, none would not raise an error # TODO, we should set the negotiate flags based on the lm level :-s # Note, this still works with 9x and N4.0 though self.flags = NegotiateFlag.NTLMSSP_TARGET |\ NegotiateFlag.NTLMSSP_TARGET_INFO |\ NegotiateFlag.NTLMSSP_KEY_128 if session_security == 'sign': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_NTLM2_KEY if session_security == 'encrypt': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_SEAL |\ NegotiateFlag.NTLMSSP_NTLM2_KEY self._wrapper = None self._session_key = None self._authenticator = authenticator self._session_security = session_security self.is_established = False def is_established(self): return self.is_established def initialize_security_context(self): """ Idiomatic Python implementation of initialize_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Generate the NTLM Negotiate Request negotiate_token = self._negotiate(self.flags) challenge_token = yield negotiate_token # Generate the Authenticate Response authenticate_token = self._challenge_response(negotiate_token, challenge_token) yield authenticate_token def aquire_security_context(self): """ Idiomatic Python implementation of aquire_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Accept the negotiate token negotiate_token = (yield) # Generate the Challenge token authenticate_token = yield self._challenge(negotiate_token) # check the authenticate token #authenticate_token raise Exception("aquire_security_context is not yet implemented") def unwrap_message(self, message, signature): """ Verifies the supplied signature against the message and decrypts the message if 'confidentiality' was negotiated. A SignatureException is raised if the signature cannot be parsed or the version is unsupported A SequenceException is raised if the sequence number in the signature is incorrect A ChecksumException is raised if the in the signature checksum is invalid :return: The decrypted message """ if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.unwrap(message, signature) def _negotiate(self, flags): # returns the response return Negotiate(flags, self._authenticator.get_domain(), self._hostname).get_data() def _challenge_response(self, negotiate_token, challenge_token): challenge = Challenge() challenge.from_string(challenge_token) flags = challenge['flags'] nonce = challenge['challenge'] challenge_target = challenge['target_info_fields'] # Compute the ntlm response; this depends on an interplay between the ntlm challenge flags and the settings # used to construct the 'authenticator' object ntlm_response, session_key, target_info = self._authenticator.get_ntlm_response(flags, nonce, challenge_target) # 3.1.5.2.1 Client Receives a CHALLENGE_MESSAGE # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD # NOT send the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen #### TODO Fix lm_response session key if challenge_target is None and target_info is None: lm_response = '' else: lm_response, fix_me = self._authenticator.get_lm_response(flags, nonce) # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If the we negotiated key exchange, generate a new new master key for the session, this is RC4-encrypted # with the previously selected session key. # "This capability SHOULD be used because it improves security for message integrity or confidentiality" if flags & NegotiateFlag.NTLMSSP_KEY_EXCHANGE: cipher = Cipher(algorithms.ARC4(session_key), mode=None, backend=default_backend()).encryptor() session_key = os.urandom(16) exported_session_key = cipher.update(session_key) else: exported_session_key = session_key # Ensure the negotiated flags guarantee at least the minimum level of session security required by the # client when the context was constructed if 'encrypt' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SEAL: raise Exception("failed to negotiate session encryption") if 'sign' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SIGN: raise Exception("failed to negotiate session encryption") authenticate = ChallengeResponse(flags, lm_response, ntlm_response, self._authenticator.get_domain(), self._authenticator.get_username(), exported_session_key) # If the authenticate response has the MIC flag set, we must calculate and set the mic field the 'authenticator' # object determines when mic code generation is required and sets this flag if _mic_required(target_info): _add_mic(authenticate, session_key, negotiate_token, challenge_token) # If session security was negotiated we should construct an appropriate object to perform the subsequent # message wrapping and unwrapping # We need a factory which will construct the correct wrapper based on the flags, it needs to support # NTLM1 and NTLM2 Session Security. This is tricky, because it needs the correct key based on flags # for NTLM1, 'Negotiate Lan Manager Key' determines if we need a User Session Key or Lan Manager Session Key # this needs to be done in advance by whatever computes the master key and key exchange key # #logger.debug("Negotiated Session Key: %s", AsHex(session_key)) if flags & NegotiateFlag.NTLMSSP_SEAL: self._wrapper = Ntlm2Sealing(flags, session_key, 'client') elif flags & NegotiateFlag.NTLMSSP_SIGN: self._wrapper = Ntlm2Signing(flags, session_key) # TODO: Check the returned flags are set correctly #if flags & NegotiateFlag.NTLMSSP_VERSION: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_VERSION #if flags & NegotiateFlag.NTLMSSP_NTLM_KEY: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_NTLM_KEY self.is_established = True self.flags = flags return authenticate.get_data()
ianclegg/ntlmlib
ntlmlib/context.py
NtlmContext.unwrap_message
python
def unwrap_message(self, message, signature): if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.unwrap(message, signature)
Verifies the supplied signature against the message and decrypts the message if 'confidentiality' was negotiated. A SignatureException is raised if the signature cannot be parsed or the version is unsupported A SequenceException is raised if the sequence number in the signature is incorrect A ChecksumException is raised if the in the signature checksum is invalid :return: The decrypted message
train
https://github.com/ianclegg/ntlmlib/blob/49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05/ntlmlib/context.py#L127-L141
null
class NtlmContext(object): """ For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. """ def __init__(self, authenticator, session_security='none', **kwargs): if session_security not in ('none', 'sign', 'encrypt'): raise Exception("session_security must be none, sign or encrypt") # Initialise a random default 8 byte NTLM client challenge self._os_version = kwargs.get('version', (6, 6, 0)) # Initialise a random default 8 byte NTLM client challenge self._hostname = kwargs.get('hostname', gethostname()) # TODO, should accept a list of possible in order of preference # these should probably be 'integrity' and 'confidentiality' # encrypt, sign, none would not raise an error # TODO, we should set the negotiate flags based on the lm level :-s # Note, this still works with 9x and N4.0 though self.flags = NegotiateFlag.NTLMSSP_TARGET |\ NegotiateFlag.NTLMSSP_TARGET_INFO |\ NegotiateFlag.NTLMSSP_KEY_128 if session_security == 'sign': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_NTLM2_KEY if session_security == 'encrypt': self.flags |= NegotiateFlag.NTLMSSP_KEY_EXCHANGE |\ NegotiateFlag.NTLMSSP_ALWAYS_SIGN |\ NegotiateFlag.NTLMSSP_SIGN |\ NegotiateFlag.NTLMSSP_SEAL |\ NegotiateFlag.NTLMSSP_NTLM2_KEY self._wrapper = None self._session_key = None self._authenticator = authenticator self._session_security = session_security self.is_established = False def is_established(self): return self.is_established def initialize_security_context(self): """ Idiomatic Python implementation of initialize_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Generate the NTLM Negotiate Request negotiate_token = self._negotiate(self.flags) challenge_token = yield negotiate_token # Generate the Authenticate Response authenticate_token = self._challenge_response(negotiate_token, challenge_token) yield authenticate_token def aquire_security_context(self): """ Idiomatic Python implementation of aquire_security_context, implemented as a generator function using yield to both accept incoming and return outgoing authentication tokens :return: The response to be returned to the server """ # Accept the negotiate token negotiate_token = (yield) # Generate the Challenge token authenticate_token = yield self._challenge(negotiate_token) # check the authenticate token #authenticate_token raise Exception("aquire_security_context is not yet implemented") def wrap_message(self, message): """ Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if 'confidentiality' was negotiated, otherwise the message is left untouched. :return: A tuple containing the message signature and the optionally encrypted message """ if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.wrap(message) def _negotiate(self, flags): # returns the response return Negotiate(flags, self._authenticator.get_domain(), self._hostname).get_data() def _challenge_response(self, negotiate_token, challenge_token): challenge = Challenge() challenge.from_string(challenge_token) flags = challenge['flags'] nonce = challenge['challenge'] challenge_target = challenge['target_info_fields'] # Compute the ntlm response; this depends on an interplay between the ntlm challenge flags and the settings # used to construct the 'authenticator' object ntlm_response, session_key, target_info = self._authenticator.get_ntlm_response(flags, nonce, challenge_target) # 3.1.5.2.1 Client Receives a CHALLENGE_MESSAGE # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field, the client SHOULD # NOT send the LmChallengeResponse and SHOULD set the LmChallengeResponseLen and LmChallengeResponseMaxLen #### TODO Fix lm_response session key if challenge_target is None and target_info is None: lm_response = '' else: lm_response, fix_me = self._authenticator.get_lm_response(flags, nonce) # [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol (Page 46) # If the we negotiated key exchange, generate a new new master key for the session, this is RC4-encrypted # with the previously selected session key. # "This capability SHOULD be used because it improves security for message integrity or confidentiality" if flags & NegotiateFlag.NTLMSSP_KEY_EXCHANGE: cipher = Cipher(algorithms.ARC4(session_key), mode=None, backend=default_backend()).encryptor() session_key = os.urandom(16) exported_session_key = cipher.update(session_key) else: exported_session_key = session_key # Ensure the negotiated flags guarantee at least the minimum level of session security required by the # client when the context was constructed if 'encrypt' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SEAL: raise Exception("failed to negotiate session encryption") if 'sign' in self._session_security and not flags & NegotiateFlag.NTLMSSP_SIGN: raise Exception("failed to negotiate session encryption") authenticate = ChallengeResponse(flags, lm_response, ntlm_response, self._authenticator.get_domain(), self._authenticator.get_username(), exported_session_key) # If the authenticate response has the MIC flag set, we must calculate and set the mic field the 'authenticator' # object determines when mic code generation is required and sets this flag if _mic_required(target_info): _add_mic(authenticate, session_key, negotiate_token, challenge_token) # If session security was negotiated we should construct an appropriate object to perform the subsequent # message wrapping and unwrapping # We need a factory which will construct the correct wrapper based on the flags, it needs to support # NTLM1 and NTLM2 Session Security. This is tricky, because it needs the correct key based on flags # for NTLM1, 'Negotiate Lan Manager Key' determines if we need a User Session Key or Lan Manager Session Key # this needs to be done in advance by whatever computes the master key and key exchange key # #logger.debug("Negotiated Session Key: %s", AsHex(session_key)) if flags & NegotiateFlag.NTLMSSP_SEAL: self._wrapper = Ntlm2Sealing(flags, session_key, 'client') elif flags & NegotiateFlag.NTLMSSP_SIGN: self._wrapper = Ntlm2Signing(flags, session_key) # TODO: Check the returned flags are set correctly #if flags & NegotiateFlag.NTLMSSP_VERSION: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_VERSION #if flags & NegotiateFlag.NTLMSSP_NTLM_KEY: # flags &= 0xffffffff ^ NegotiateFlag.NTLMSSP_NTLM_KEY self.is_established = True self.flags = flags return authenticate.get_data()
Sliim/soundcloud-syncer
ssyncer/sclient.py
sclient.send_request
python
def send_request(self, url): while True: try: return urllib.request.urlopen(url) except urllib.error.HTTPError as e: raise serror( "Request `%s` failed (%s:%s)." % (url, e.__class__.__name__, e.code)) except Exception as e: choice = input(serror( "Error occured: %s - Retry? [yN]" % type(e))) if choice.strip().lower() != "y": raise serror(e)
Send a request to given url.
train
https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/sclient.py#L54-L67
null
class sclient: host = "api.soundcloud.com" port = "443" client_id = None SC_HOME = "https://www.soundcloud.com" DOWNLOAD_URL = "/tracks/%d/download?client_id=" STREAM_URL = "/tracks/%d/stream?client_id=" USER_LIKES = "/users/%s/favorites.json?offset=%d&limit=%d&client_id=" USER_TRACKS = "/users/%s/tracks.json?offset=%d&limit=%d&client_id=" USER_PLAYLISTS = "/users/%s/playlists.json?offset=%d&limit=%d&client_id=" TRACK_DATA = "/tracks/%s.json?client_id=" def __init__(self, client_id=None, **kwargs): """ Http client initialization. """ if "host" in kwargs: self.host = kwargs.get("host") if "port" in kwargs: self.port = kwargs.get("port") if not client_id: print("Attempt to get client_id..") self.client_id = self.get_client_id() print("OK, client_id = %s" % self.client_id) else: self.client_id = client_id def get_protocol(self): """ Get protocol from port to use. """ if self.port == "443": return "https" return "http" def get(self, uri): """ Send a request to given uri. """ return self.send_request( "{0}://{1}:{2}{3}{4}".format( self.get_protocol(), self.host, self.port, uri, self.client_id ) ) def get_location(self, uri): """ Send a request and get redirected url. """ return self.get(uri).geturl() def get_client_id(self): """ Attempt to get client_id from soundcloud homepage. """ # FIXME: This method doesn't works id = re.search( "\"clientID\":\"([a-z0-9]*)\"", self.send_request(self.SC_HOME).read().decode("utf-8")) if not id: raise serror("Cannot retrieve client_id.") return id.group(1)
Sliim/soundcloud-syncer
ssyncer/sclient.py
sclient.get
python
def get(self, uri): return self.send_request( "{0}://{1}:{2}{3}{4}".format( self.get_protocol(), self.host, self.port, uri, self.client_id ) )
Send a request to given uri.
train
https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/sclient.py#L69-L79
[ "def get_protocol(self):\n \"\"\" Get protocol from port to use. \"\"\"\n if self.port == \"443\":\n return \"https\"\n return \"http\"\n", "def send_request(self, url):\n \"\"\" Send a request to given url. \"\"\"\n while True:\n try:\n return urllib.request.urlopen(url)\n except urllib.error.HTTPError as e:\n raise serror(\n \"Request `%s` failed (%s:%s).\" %\n (url, e.__class__.__name__, e.code))\n except Exception as e:\n choice = input(serror(\n \"Error occured: %s - Retry? [yN]\" % type(e)))\n if choice.strip().lower() != \"y\":\n raise serror(e)\n" ]
class sclient: host = "api.soundcloud.com" port = "443" client_id = None SC_HOME = "https://www.soundcloud.com" DOWNLOAD_URL = "/tracks/%d/download?client_id=" STREAM_URL = "/tracks/%d/stream?client_id=" USER_LIKES = "/users/%s/favorites.json?offset=%d&limit=%d&client_id=" USER_TRACKS = "/users/%s/tracks.json?offset=%d&limit=%d&client_id=" USER_PLAYLISTS = "/users/%s/playlists.json?offset=%d&limit=%d&client_id=" TRACK_DATA = "/tracks/%s.json?client_id=" def __init__(self, client_id=None, **kwargs): """ Http client initialization. """ if "host" in kwargs: self.host = kwargs.get("host") if "port" in kwargs: self.port = kwargs.get("port") if not client_id: print("Attempt to get client_id..") self.client_id = self.get_client_id() print("OK, client_id = %s" % self.client_id) else: self.client_id = client_id def get_protocol(self): """ Get protocol from port to use. """ if self.port == "443": return "https" return "http" def send_request(self, url): """ Send a request to given url. """ while True: try: return urllib.request.urlopen(url) except urllib.error.HTTPError as e: raise serror( "Request `%s` failed (%s:%s)." % (url, e.__class__.__name__, e.code)) except Exception as e: choice = input(serror( "Error occured: %s - Retry? [yN]" % type(e))) if choice.strip().lower() != "y": raise serror(e) def get_location(self, uri): """ Send a request and get redirected url. """ return self.get(uri).geturl() def get_client_id(self): """ Attempt to get client_id from soundcloud homepage. """ # FIXME: This method doesn't works id = re.search( "\"clientID\":\"([a-z0-9]*)\"", self.send_request(self.SC_HOME).read().decode("utf-8")) if not id: raise serror("Cannot retrieve client_id.") return id.group(1)
Sliim/soundcloud-syncer
ssyncer/sclient.py
sclient.get_client_id
python
def get_client_id(self): # FIXME: This method doesn't works id = re.search( "\"clientID\":\"([a-z0-9]*)\"", self.send_request(self.SC_HOME).read().decode("utf-8")) if not id: raise serror("Cannot retrieve client_id.") return id.group(1)
Attempt to get client_id from soundcloud homepage.
train
https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/sclient.py#L85-L95
[ "def send_request(self, url):\n \"\"\" Send a request to given url. \"\"\"\n while True:\n try:\n return urllib.request.urlopen(url)\n except urllib.error.HTTPError as e:\n raise serror(\n \"Request `%s` failed (%s:%s).\" %\n (url, e.__class__.__name__, e.code))\n except Exception as e:\n choice = input(serror(\n \"Error occured: %s - Retry? [yN]\" % type(e)))\n if choice.strip().lower() != \"y\":\n raise serror(e)\n" ]
class sclient: host = "api.soundcloud.com" port = "443" client_id = None SC_HOME = "https://www.soundcloud.com" DOWNLOAD_URL = "/tracks/%d/download?client_id=" STREAM_URL = "/tracks/%d/stream?client_id=" USER_LIKES = "/users/%s/favorites.json?offset=%d&limit=%d&client_id=" USER_TRACKS = "/users/%s/tracks.json?offset=%d&limit=%d&client_id=" USER_PLAYLISTS = "/users/%s/playlists.json?offset=%d&limit=%d&client_id=" TRACK_DATA = "/tracks/%s.json?client_id=" def __init__(self, client_id=None, **kwargs): """ Http client initialization. """ if "host" in kwargs: self.host = kwargs.get("host") if "port" in kwargs: self.port = kwargs.get("port") if not client_id: print("Attempt to get client_id..") self.client_id = self.get_client_id() print("OK, client_id = %s" % self.client_id) else: self.client_id = client_id def get_protocol(self): """ Get protocol from port to use. """ if self.port == "443": return "https" return "http" def send_request(self, url): """ Send a request to given url. """ while True: try: return urllib.request.urlopen(url) except urllib.error.HTTPError as e: raise serror( "Request `%s` failed (%s:%s)." % (url, e.__class__.__name__, e.code)) except Exception as e: choice = input(serror( "Error occured: %s - Retry? [yN]" % type(e))) if choice.strip().lower() != "y": raise serror(e) def get(self, uri): """ Send a request to given uri. """ return self.send_request( "{0}://{1}:{2}{3}{4}".format( self.get_protocol(), self.host, self.port, uri, self.client_id ) ) def get_location(self, uri): """ Send a request and get redirected url. """ return self.get(uri).geturl()
Sliim/soundcloud-syncer
ssyncer/splaylist.py
splaylist.write_playlist_file
python
def write_playlist_file(self, localdir): path = "{0}/playlists".format(localdir) if not os.path.exists(path): os.makedirs(path) filepath = "{0}/{1}".format(path, self.gen_filename()) playlist = open(filepath, "w") for track in self.get_tracks(): playlist.write("{0}/{1}.mp3\n".format( os.path.abspath(track.gen_localdir(localdir)), track.gen_filename())) playlist.close()
Check if playlist exists in local directory.
train
https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/splaylist.py#L76-L88
[ "def get_tracks(self, playlist_data=None, *args):\n \"\"\" Get playlist's tracks. \"\"\"\n return self.get(\"tracks\")\n", "def gen_filename(self):\n \"\"\" Generate local filename for this playlist. \"\"\"\n return \"{0}.m3u\".format(self.get(\"permalink\"))\n" ]
class splaylist: client = None metadata = {} def __init__(self, playlist_data, **kwargs): """ Playlist object initialization, load playlist metadata. """ if "client" in kwargs: self.client = kwargs.get("client") elif "client_id" in kwargs: self.client = sclient(kwargs.get("client_id")) else: self.client = sclient() tracks = [] for track in playlist_data["tracks"]: tracks.append(strack(track, client=self.client)) def map(key, data): return str(data[key]) if key in data else "" self.metadata = { "duration": map("duration", playlist_data), "release-day": map("release_day", playlist_data), "permalink-url": map("permalink_url", playlist_data), "reposts-count": map("reposts_count", playlist_data), "genre": map("genre", playlist_data), "permalink": map("permalink", playlist_data), "purchase-url": map("purchase_url", playlist_data), "release-month": map("release_month", playlist_data), "description": map("description", playlist_data), "uri": map("uri", playlist_data), "label-name": map("label_name", playlist_data), "tag-list": map("tag_list", playlist_data), "release-year": map("release_year", playlist_data), "track-count": map("track_count", playlist_data), "user-id": map("user_id", playlist_data), "last-modified": map("last_modified", playlist_data), "license": map("license", playlist_data), "tracks": tracks } def get(self, key): """ Get playlist metadata value from a given key. """ if key in self.metadata: return self.metadata[key] return None def get_tracks(self, playlist_data=None, *args): """ Get playlist's tracks. """ return self.get("tracks") def gen_filename(self): """ Generate local filename for this playlist. """ return "{0}.m3u".format(self.get("permalink"))
Sliim/soundcloud-syncer
ssyncer/suser.py
suser.get_likes
python
def get_likes(self, offset=0, limit=50): response = self.client.get( self.client.USER_LIKES % (self.name, offset, limit)) return self._parse_response(response, strack)
Get user's likes.
train
https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/suser.py#L38-L42
[ "def get(self, uri):\n \"\"\" Send a request to given uri. \"\"\"\n return self.send_request(\n \"{0}://{1}:{2}{3}{4}\".format(\n self.get_protocol(),\n self.host,\n self.port,\n uri,\n self.client_id\n )\n )\n", "def _parse_response(self, response, target_object=strack):\n \"\"\" Generic response parser method \"\"\"\n objects = json.loads(response.read().decode(\"utf-8\"))\n list = []\n for obj in objects:\n list.append(target_object(obj, client=self.client))\n return list\n" ]
class suser: name = None client = None def __init__(self, username, **kwargs): """ Initialize soundcloud's user object. """ self.name = username if "client" in kwargs: self.client = kwargs.get("client") elif "client_id" in kwargs: self.client = sclient(kwargs.get("client_id")) else: self.client = sclient() def get_tracks(self, offset=0, limit=50): """ Get user's tracks. """ response = self.client.get( self.client.USER_TRACKS % (self.name, offset, limit)) return self._parse_response(response, strack) def get_playlists(self, offset=0, limit=50): """ Get user's playlists. """ response = self.client.get( self.client.USER_PLAYLISTS % (self.name, offset, limit)) return self._parse_response(response, splaylist) return playlists def _parse_response(self, response, target_object=strack): """ Generic response parser method """ objects = json.loads(response.read().decode("utf-8")) list = [] for obj in objects: list.append(target_object(obj, client=self.client)) return list