summaryrefslogtreecommitdiff
path: root/src/leap
diff options
context:
space:
mode:
Diffstat (limited to 'src/leap')
-rw-r--r--src/leap/bitmask/_version.py489
-rw-r--r--src/leap/bitmask/auth/auth.py336
-rw-r--r--src/leap/bitmask/auth/exceptions.py65
-rw-r--r--src/leap/bitmask/auth/srp_session.py7
4 files changed, 418 insertions, 479 deletions
diff --git a/src/leap/bitmask/_version.py b/src/leap/bitmask/_version.py
index d64032a7..4ac29504 100644
--- a/src/leap/bitmask/_version.py
+++ b/src/leap/bitmask/_version.py
@@ -1,483 +1,14 @@
-# This file helps to compute a version number in source trees obtained from
-# git-archive tarball (such as those provided by githubs download-from-tag
-# feature). Distribution tarballs (built by setup.py sdist) and build
-# directories (produced by setup.py build) will contain a much shorter file
-# that just contains the computed version number.
-# This file is released into the public domain. Generated by
-# versioneer-0.16 (https://github.com/warner/python-versioneer)
+# This file was generated by the `freeze_debianver` command in setup.py
+# Using 'versioneer.py' (0.16) from
+# revision-control system data, or from the parent directory name of an
+# unpacked source archive. Distribution tarballs contain a pre-generated copy
+# of this file.
-"""Git implementation of _version.py."""
+version_version = '0.9.2'
+full_revisionid = '5f9c136abc20134764ca970c52b04c69e6e64199'
-import errno
-import os
-import re
-import subprocess
-import sys
-
-def get_keywords():
- """Get the keywords needed to look up the version information."""
- # these strings will be replaced by git during git-archive.
- # setup.py/versioneer.py will grep for the variable names, so they must
- # each be defined on a line of their own. _version.py will just call
- # get_keywords().
- git_refnames = "$Format:%d$"
- git_full = "$Format:%H$"
- keywords = {"refnames": git_refnames, "full": git_full}
- return keywords
-
-
-class VersioneerConfig:
- """Container for Versioneer configuration parameters."""
-
-
-def get_config():
- """Create, populate and return the VersioneerConfig() object."""
- # these strings are filled in when 'setup.py versioneer' creates
- # _version.py
- cfg = VersioneerConfig()
- cfg.VCS = "git"
- cfg.style = "pep440"
- cfg.tag_prefix = ""
- cfg.parentdir_prefix = "None"
- cfg.versionfile_source = "src/leap/bitmask/_version.py"
- cfg.verbose = False
- return cfg
-
-
-class NotThisMethod(Exception):
- """Exception raised if a method is not valid for the current scenario."""
-
-
-LONG_VERSION_PY = {}
-HANDLERS = {}
-
-
-def register_vcs_handler(vcs, method): # decorator
- """Decorator to mark a method as the handler for a particular VCS."""
- def decorate(f):
- """Store f in HANDLERS[vcs][method]."""
- if vcs not in HANDLERS:
- HANDLERS[vcs] = {}
- HANDLERS[vcs][method] = f
- return f
- return decorate
-
-
-def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
- """Call the given command(s)."""
- assert isinstance(commands, list)
- p = None
- for c in commands:
- try:
- dispcmd = str([c] + args)
- # remember shell=False, so use git.cmd on windows, not just git
- p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
- stderr=(subprocess.PIPE if hide_stderr
- else None))
- break
- except EnvironmentError:
- e = sys.exc_info()[1]
- if e.errno == errno.ENOENT:
- continue
- if verbose:
- print("unable to run %s" % dispcmd)
- print(e)
- return None
- else:
- if verbose:
- print("unable to find command, tried %s" % (commands,))
- return None
- stdout = p.communicate()[0].strip()
- if sys.version_info[0] >= 3:
- stdout = stdout.decode()
- if p.returncode != 0:
- if verbose:
- print("unable to run %s (error)" % dispcmd)
- return None
- return stdout
-
-
-def versions_from_parentdir(parentdir_prefix, root, verbose):
- """Try to determine the version from the parent directory name.
-
- Source tarballs conventionally unpack into a directory that includes
- both the project name and a version string.
- """
- dirname = os.path.basename(root)
- if not dirname.startswith(parentdir_prefix):
- if verbose:
- print("guessing rootdir is '%s', but '%s' doesn't start with "
- "prefix '%s'" % (root, dirname, parentdir_prefix))
- raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
- return {"version": dirname[len(parentdir_prefix):],
- "full-revisionid": None,
- "dirty": False, "error": None}
-
-
-@register_vcs_handler("git", "get_keywords")
-def git_get_keywords(versionfile_abs):
- """Extract version information from the given file."""
- # the code embedded in _version.py can just fetch the value of these
- # keywords. When used from setup.py, we don't want to import _version.py,
- # so we do it with a regexp instead. This function is not used from
- # _version.py.
- keywords = {}
- try:
- f = open(versionfile_abs, "r")
- for line in f.readlines():
- if line.strip().startswith("git_refnames ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["refnames"] = mo.group(1)
- if line.strip().startswith("git_full ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["full"] = mo.group(1)
- f.close()
- except EnvironmentError:
- pass
- return keywords
-
-
-@register_vcs_handler("git", "keywords")
-def git_versions_from_keywords(keywords, tag_prefix, verbose):
- """Get version information from git keywords."""
- if not keywords:
- raise NotThisMethod("no keywords at all, weird")
- refnames = keywords["refnames"].strip()
- if refnames.startswith("$Format"):
- if verbose:
- print("keywords are unexpanded, not using")
- raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
- refs = set([r.strip() for r in refnames.strip("()").split(",")])
- # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
- # just "foo-1.0". If we see a "tag: " prefix, prefer those.
- TAG = "tag: "
- tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
- if not tags:
- # Either we're using git < 1.8.3, or there really are no tags. We use
- # a heuristic: assume all version tags have a digit. The old git %d
- # expansion behaves like git log --decorate=short and strips out the
- # refs/heads/ and refs/tags/ prefixes that would let us distinguish
- # between branches and tags. By ignoring refnames without digits, we
- # filter out many common branch names like "release" and
- # "stabilization", as well as "HEAD" and "master".
- tags = set([r for r in refs if re.search(r'\d', r)])
- if verbose:
- print("discarding '%s', no digits" % ",".join(refs - tags))
- if verbose:
- print("likely tags: %s" % ",".join(sorted(tags)))
- for ref in sorted(tags):
- # sorting will prefer e.g. "2.0" over "2.0rc1"
- if ref.startswith(tag_prefix):
- r = ref[len(tag_prefix):]
- if verbose:
- print("picking %s" % r)
- return {"version": r,
- "full-revisionid": keywords["full"].strip(),
- "dirty": False, "error": None
- }
- # no suitable tags, so version is "0+unknown", but full hex is still there
- if verbose:
- print("no suitable tags, using unknown + full revision id")
- return {"version": "0+unknown",
- "full-revisionid": keywords["full"].strip(),
- "dirty": False, "error": "no suitable tags"}
-
-
-@register_vcs_handler("git", "pieces_from_vcs")
-def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
- """Get version from 'git describe' in the root of the source tree.
-
- This only gets called if the git-archive 'subst' keywords were *not*
- expanded, and _version.py hasn't already been rewritten with a short
- version string, meaning we're inside a checked out source tree.
- """
- if not os.path.exists(os.path.join(root, ".git")):
- if verbose:
- print("no .git in %s" % root)
- raise NotThisMethod("no .git directory")
-
- GITS = ["git"]
- if sys.platform == "win32":
- GITS = ["git.cmd", "git.exe"]
- # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
- # if there isn't one, this yields HEX[-dirty] (no NUM)
- describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
- "--always", "--long",
- "--match", "%s*" % tag_prefix],
- cwd=root)
- # --long was added in git-1.5.5
- if describe_out is None:
- raise NotThisMethod("'git describe' failed")
- describe_out = describe_out.strip()
- full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
- if full_out is None:
- raise NotThisMethod("'git rev-parse' failed")
- full_out = full_out.strip()
-
- pieces = {}
- pieces["long"] = full_out
- pieces["short"] = full_out[:7] # maybe improved later
- pieces["error"] = None
-
- # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
- # TAG might have hyphens.
- git_describe = describe_out
-
- # look for -dirty suffix
- dirty = git_describe.endswith("-dirty")
- pieces["dirty"] = dirty
- if dirty:
- git_describe = git_describe[:git_describe.rindex("-dirty")]
-
- # now we have TAG-NUM-gHEX or HEX
-
- if "-" in git_describe:
- # TAG-NUM-gHEX
- mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
- if not mo:
- # unparseable. Maybe git-describe is misbehaving?
- pieces["error"] = ("unable to parse git-describe output: '%s'"
- % describe_out)
- return pieces
-
- # tag
- full_tag = mo.group(1)
- if not full_tag.startswith(tag_prefix):
- if verbose:
- fmt = "tag '%s' doesn't start with prefix '%s'"
- print(fmt % (full_tag, tag_prefix))
- pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
- % (full_tag, tag_prefix))
- return pieces
- pieces["closest-tag"] = full_tag[len(tag_prefix):]
-
- # distance: number of commits since tag
- pieces["distance"] = int(mo.group(2))
-
- # commit: short hex revision ID
- pieces["short"] = mo.group(3)
-
- else:
- # HEX: no tags
- pieces["closest-tag"] = None
- count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
- cwd=root)
- pieces["distance"] = int(count_out) # total number of commits
-
- return pieces
-
-
-def plus_or_dot(pieces):
- """Return a + if we don't already have one, else return a ."""
- if "+" in pieces.get("closest-tag", ""):
- return "."
- return "+"
-
-
-def render_pep440(pieces):
- """Build up version string, with post-release "local version identifier".
-
- Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
- get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
-
- Exceptions:
- 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += plus_or_dot(pieces)
- rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0+untagged.%d.g%s" % (pieces["distance"],
- pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_pre(pieces):
- """TAG[.post.devDISTANCE] -- No -dirty.
-
- Exceptions:
- 1: no tags. 0.post.devDISTANCE
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"]:
- rendered += ".post.dev%d" % pieces["distance"]
- else:
- # exception #1
- rendered = "0.post.dev%d" % pieces["distance"]
- return rendered
-
-
-def render_pep440_post(pieces):
- """TAG[.postDISTANCE[.dev0]+gHEX] .
-
- The ".dev0" means dirty. Note that .dev0 sorts backwards
- (a dirty tree will appear "older" than the corresponding clean one),
- but you shouldn't be releasing software with -dirty anyways.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%s" % pieces["short"]
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += "+g%s" % pieces["short"]
- return rendered
-
-
-def render_pep440_old(pieces):
- """TAG[.postDISTANCE[.dev0]] .
-
- The ".dev0" means dirty.
-
- Eexceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- return rendered
-
-
-def render_git_describe(pieces):
- """TAG[-DISTANCE-gHEX][-dirty].
-
- Like 'git describe --tags --dirty --always'.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"]:
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render_git_describe_long(pieces):
- """TAG-DISTANCE-gHEX[-dirty].
-
- Like 'git describe --tags --dirty --always -long'.
- The distance/hash is unconditional.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render(pieces, style):
- """Render the given version pieces into the requested style."""
- if pieces["error"]:
- return {"version": "unknown",
- "full-revisionid": pieces.get("long"),
- "dirty": None,
- "error": pieces["error"]}
-
- if not style or style == "default":
- style = "pep440" # the default
-
- if style == "pep440":
- rendered = render_pep440(pieces)
- elif style == "pep440-pre":
- rendered = render_pep440_pre(pieces)
- elif style == "pep440-post":
- rendered = render_pep440_post(pieces)
- elif style == "pep440-old":
- rendered = render_pep440_old(pieces)
- elif style == "git-describe":
- rendered = render_git_describe(pieces)
- elif style == "git-describe-long":
- rendered = render_git_describe_long(pieces)
- else:
- raise ValueError("unknown style '%s'" % style)
-
- return {"version": rendered, "full-revisionid": pieces["long"],
- "dirty": pieces["dirty"], "error": None}
-
-
-def get_versions():
- """Get version information or return default if unable to do so."""
- # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
- # __file__, we can work backwards from there to the root. Some
- # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
- # case we can only use expanded keywords.
-
- cfg = get_config()
- verbose = cfg.verbose
-
- try:
- return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
- verbose)
- except NotThisMethod:
- pass
-
- try:
- root = os.path.realpath(__file__)
- # versionfile_source is the relative path from the top of the source
- # tree (where the .git directory might live) to this file. Invert
- # this to find the root from __file__.
- for i in cfg.versionfile_source.split('/'):
- root = os.path.dirname(root)
- except NameError:
- return {"version": "0+unknown", "full-revisionid": None,
- "dirty": None,
- "error": "unable to find root of source tree"}
-
- try:
- pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
- return render(pieces, cfg.style)
- except NotThisMethod:
- pass
-
- try:
- if cfg.parentdir_prefix:
- return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
- except NotThisMethod:
- pass
-
- return {"version": "0+unknown", "full-revisionid": None,
- "dirty": None,
- "error": "unable to compute version"}
+def get_versions(default={}, verbose=False):
+ return {'version': version_version,
+ 'full-revisionid': full_revisionid}
diff --git a/src/leap/bitmask/auth/auth.py b/src/leap/bitmask/auth/auth.py
new file mode 100644
index 00000000..03065571
--- /dev/null
+++ b/src/leap/bitmask/auth/auth.py
@@ -0,0 +1,336 @@
+import binascii
+import logging
+import os.path
+import requests
+import srp
+import json
+import re
+
+from requests.adapters import HTTPAdapter
+
+from leap.exceptions import (SRPAuthenticationError,
+ SRPAuthConnectionError,
+ SRPAuthBadStatusCode,
+ SRPAuthNoSalt,
+ SRPAuthNoB,
+ SRPAuthBadDataFromServer,
+ SRPAuthBadUserOrPassword,
+ SRPAuthVerificationFailed,
+ SRPAuthNoSessionId)
+
+from leap.srp_session import SRPSession
+
+logger = logging.getLogger(__name__)
+
+
+class SRPAuth(object):
+
+ def __init__(self, api_uri, verify_certificate=True, api_version=1):
+ self.api_uri = api_uri
+ self.api_version = api_version
+
+ if verify_certificate is None:
+ verify_certificate = True
+
+ if isinstance(verify_certificate, (str, unicode)) and not os.path.isfile(verify_certificate):
+ raise ValueError(
+ 'Path {0} is not a valid file'.format(verify_certificate))
+
+ self.verify_certificate = verify_certificate
+
+ def reset_session(self):
+ adapter = HTTPAdapter(max_retries=50)
+ self._session = requests.session()
+ self._session.mount('https://', adapter)
+ self.session_id = None
+
+ def _authentication_preprocessing(self, username, password):
+
+ logger.debug('Authentication preprocessing...')
+
+ user = srp.User(username.encode('utf-8'),
+ password.encode('utf-8'),
+ srp.SHA256, srp.NG_1024)
+ _, A = user.start_authentication()
+
+ return user, A
+
+ def _start_authentication(self, username, A):
+
+ logger.debug('Starting authentication process...')
+ try:
+ auth_data = {
+ 'login': username,
+ 'A': binascii.hexlify(A)
+ }
+ sessions_url = '%s/%s/%s/' % \
+ (self.api_uri,
+ self.api_version,
+ 'sessions')
+
+ verify_certificate = self.verify_certificate
+
+ init_session = self._session.post(sessions_url,
+ data=auth_data,
+ verify=verify_certificate,
+ timeout=30)
+ except requests.exceptions.ConnectionError as e:
+ logger.error('No connection made (salt): {0!r}'.format(e))
+ raise SRPAuthConnectionError()
+ except Exception as e:
+ logger.error('Unknown error: %r' % (e,))
+ raise SRPAuthenticationError()
+
+ if init_session.status_code not in (200,):
+ logger.error('No valid response (salt): '
+ 'Status code = %r. Content: %r' %
+ (init_session.status_code, init_session.content))
+ if init_session.status_code == 422:
+ logger.error('Invalid username or password.')
+ raise SRPAuthBadUserOrPassword()
+
+ logger.error('There was a problem with authentication.')
+ raise SRPAuthBadStatusCode()
+
+ json_content = json.loads(init_session.content)
+ salt = json_content.get('salt', None)
+ B = json_content.get('B', None)
+
+ if salt is None:
+ logger.error('The server didn\'t send the salt parameter.')
+ raise SRPAuthNoSalt()
+ if B is None:
+ logger.error('The server didn\'t send the B parameter.')
+ raise SRPAuthNoB()
+
+ return salt, B
+
+ def _process_challenge(self, user, salt_B, username):
+ logger.debug('Processing challenge...')
+ try:
+ salt, B = salt_B
+ unhex_salt = _safe_unhexlify(salt)
+ unhex_B = _safe_unhexlify(B)
+ except (TypeError, ValueError) as e:
+ logger.error('Bad data from server: %r' % (e,))
+ raise SRPAuthBadDataFromServer()
+ M = user.process_challenge(unhex_salt, unhex_B)
+
+ auth_url = '%s/%s/%s/%s' % (self.api_uri,
+ self.api_version,
+ 'sessions',
+ username)
+
+ auth_data = {
+ 'client_auth': binascii.hexlify(M)
+ }
+
+ try:
+ auth_result = self._session.put(auth_url,
+ data=auth_data,
+ verify=self.verify_certificate,
+ timeout=30)
+ except requests.exceptions.ConnectionError as e:
+ logger.error('No connection made (HAMK): %r' % (e,))
+ raise SRPAuthConnectionError()
+
+ if auth_result.status_code == 422:
+ error = ''
+ try:
+ error = json.loads(auth_result.content).get('errors', '')
+ except ValueError:
+ logger.error('Problem parsing the received response: %s'
+ % (auth_result.content,))
+ except AttributeError:
+ logger.error('Expecting a dict but something else was '
+ 'received: %s', (auth_result.content,))
+ logger.error('[%s] Wrong password (HAMK): [%s]' %
+ (auth_result.status_code, error))
+ raise SRPAuthBadUserOrPassword()
+
+ if auth_result.status_code not in (200,):
+ logger.error('No valid response (HAMK): '
+ 'Status code = %s. Content = %r' %
+ (auth_result.status_code, auth_result.content))
+ raise SRPAuthBadStatusCode()
+
+ return json.loads(auth_result.content)
+
+ def _extract_data(self, json_content):
+
+ try:
+ M2 = json_content.get('M2', None)
+ uuid = json_content.get('id', None)
+ token = json_content.get('token', None)
+ except Exception as e:
+ logger.error(e)
+ raise SRPAuthBadDataFromServer()
+
+ if M2 is None or uuid is None:
+ logger.error('Something went wrong. Content = %r' %
+ (json_content,))
+ raise SRPAuthBadDataFromServer()
+
+ return uuid, token, M2
+
+ def _verify_session(self, user, M2):
+
+ logger.debug('Verifying session...')
+ try:
+ unhex_M2 = _safe_unhexlify(M2)
+ except TypeError:
+ logger.error('Bad data from server (HAMK)')
+ raise SRPAuthBadDataFromServer()
+
+ user.verify_session(unhex_M2)
+
+ if not user.authenticated():
+ logger.error('Auth verification failed.')
+ raise SRPAuthVerificationFailed()
+ logger.debug('Session verified.')
+
+ session_id = self._session.cookies.get('_session_id', None)
+ if not session_id:
+ logger.error('Bad cookie from server (missing _session_id)')
+ raise SRPAuthNoSessionId()
+
+ logger.debug('SUCCESS LOGIN')
+ return session_id
+
+ def authenticate(self, username, password):
+
+ self.reset_session()
+
+ user, A = self._authentication_preprocessing(username, password)
+ salt_B = self._start_authentication(username, A)
+
+ json_content = self._process_challenge(user, salt_B, username)
+
+ uuid, token, M2 = self._extract_data(json_content)
+ session_id = self._verify_session(user, M2)
+
+ self.session_id = session_id
+
+ return SRPSession(username, token, uuid, session_id)
+
+ def logout(self):
+ logger.debug('Starting logout...')
+
+ if self.session_id is None:
+ logger.debug('Already logged out')
+ return
+
+ logout_url = '%s/%s/%s/' % (self.api_uri,
+ self.api_version,
+ 'logout')
+ try:
+ self._session.delete(logout_url,
+ data=self.session_id,
+ verify=self.verify_certificate,
+ timeout=30)
+ self.reset_session()
+ except Exception as e:
+ logger.warning('Something went wrong with the logout: %r' %
+ (e,))
+ raise
+ else:
+ logger.debug('Successfully logged out.')
+
+ def change_password(self,
+ username,
+ current_password,
+ new_password,
+ token,
+ uuid):
+
+ if self.session_id is None:
+ logger.debug('Already logged out')
+ return
+
+ url = '%s/%s/users/%s.json' % (
+ self.api_uri,
+ self.api_version,
+ uuid)
+
+ salt, verifier = srp.create_salted_verification_key(
+ username, new_password.encode('utf-8'),
+ srp.SHA256, srp.NG_1024)
+
+ cookies = {'_session_id': self.session_id}
+ headers = {
+ 'Authorization':
+ 'Token token={0}'.format(token)
+ }
+ user_data = {
+ 'user[password_verifier]': binascii.hexlify(verifier),
+ 'user[password_salt]': binascii.hexlify(salt)
+ }
+
+ change_password = self._session.put(
+ url, data=user_data,
+ verify=self.verify_certificate,
+ cookies=cookies,
+ timeout=30,
+ headers=headers)
+
+ change_password.raise_for_status()
+
+ def register(self, username, password):
+ self.reset_session()
+
+ username = username.encode('utf-8')
+ password = password.encode('utf-8')
+
+ validate_username(username)
+
+ salt, verifier = srp.create_salted_verification_key(
+ username,
+ password,
+ srp.SHA256,
+ srp.NG_1024)
+
+ user_data = {
+ 'user[login]': username,
+ 'user[password_verifier]': binascii.hexlify(verifier),
+ 'user[password_salt]': binascii.hexlify(salt)
+ }
+
+ url = "%s/%s/users" % (
+ self.api_uri,
+ self.api_version)
+
+ logger.debug("Registering user: %s" % username)
+
+ try:
+ response = self._session.post(
+ url,
+ data=user_data,
+ timeout=30,
+ verify=self.verify_certificate)
+
+ except requests.exceptions.RequestException as exc:
+ logger.error(exc.message)
+ raise
+
+ if not response.ok:
+ try:
+ json_content = json.loads(response.content)
+ error_msg = json_content.get("errors").get("login")[0]
+ if not error_msg.istitle():
+ error_msg = "%s %s" % (username, error_msg)
+ logger.error(error_msg)
+ except Exception as e:
+ logger.error("Unknown error: %s" % e.message)
+
+ return response.ok
+
+
+def _safe_unhexlify(val):
+ return binascii.unhexlify(val) \
+ if (len(val) % 2 == 0) else binascii.unhexlify('0' + val)
+
+
+def validate_username(username):
+ accepted_characters = '^[a-z0-9\-\_\.]*$'
+ if not re.match(accepted_characters, username):
+ raise ValueError('Only lowercase letters, digits, . - and _ allowed.')
diff --git a/src/leap/bitmask/auth/exceptions.py b/src/leap/bitmask/auth/exceptions.py
new file mode 100644
index 00000000..3dea3f76
--- /dev/null
+++ b/src/leap/bitmask/auth/exceptions.py
@@ -0,0 +1,65 @@
+class SRPAuthenticationError(Exception):
+ """
+ Exception raised for authentication errors
+ """
+ pass
+
+
+class SRPAuthConnectionError(SRPAuthenticationError):
+ """
+ Exception raised when there's a connection error
+ """
+ pass
+
+
+class SRPAuthBadStatusCode(SRPAuthenticationError):
+ """
+ Exception raised when we received an unknown bad status code
+ """
+ pass
+
+
+class SRPAuthNoSalt(SRPAuthenticationError):
+ """
+ Exception raised when we don't receive the salt param at a
+ specific point in the auth process
+ """
+ pass
+
+
+class SRPAuthNoB(SRPAuthenticationError):
+ """
+ Exception raised when we don't receive the B param at a specific
+ point in the auth process
+ """
+ pass
+
+
+class SRPAuthBadDataFromServer(SRPAuthenticationError):
+ """
+ Generic exception when we receive bad data from the server.
+ """
+ pass
+
+
+class SRPAuthBadUserOrPassword(SRPAuthenticationError):
+ """
+ Exception raised when the user provided a bad password to auth.
+ """
+ pass
+
+
+class SRPAuthVerificationFailed(SRPAuthenticationError):
+ """
+ Exception raised when we can't verify the SRP data received from
+ the server.
+ """
+ pass
+
+
+class SRPAuthNoSessionId(SRPAuthenticationError):
+ """
+ Exception raised when we don't receive a session id from the
+ server.
+ """
+ pass
diff --git a/src/leap/bitmask/auth/srp_session.py b/src/leap/bitmask/auth/srp_session.py
new file mode 100644
index 00000000..861a7cc0
--- /dev/null
+++ b/src/leap/bitmask/auth/srp_session.py
@@ -0,0 +1,7 @@
+class SRPSession(object):
+
+ def __init__(self, username, token, uuid, session_id):
+ self.username = username
+ self.token = token
+ self.uuid = uuid
+ self.session_id = session_id