launch editor with decrypted password database
767856
def launch_editor(ctx, file):
    """"""
    # do not use EDITOR environment variable (rather force user to make a concious choice)
    editor = os.environ.get("PW_EDITOR")
    if not editor:
        click.echo("error: no editor set in PW_EDITOR environment variables")
        ctx.exit(1)

    # verify that database file is present
    if not os.path.exists(file):
        click.echo("error: password store not found at '%s'" % file, err=True)
        ctx.exit(1)

    # load source (decrypting if necessary)
    is_encrypted = _gpg.is_encrypted(file)
    if is_encrypted:
        original = _gpg.decrypt(file)
    else:
        original = open(file, "rb").read()

    # if encrypted, determine recipient
    if is_encrypted:
        recipient = os.environ.get("PW_GPG_RECIPIENT")
        if not recipient:
            click.echo(
                "error: no recipient set in PW_GPG_RECIPIENT environment variables"
            )
            ctx.exit(1)

    # launch the editor
    ext = _gpg.unencrypted_ext(file)
    modified = click.edit(
        original.decode("utf-8"), editor=editor, require_save=True, extension=ext
    )
    if modified is None:
        click.echo("not modified")
        return
    modified = modified.encode("utf-8")

    # not encrypted? simply overwrite file
    if not is_encrypted:
        with open(file, "wb") as fp:
            fp.write(modified)
        return

    # otherwise, the process is somewhat more complicated
    _gpg.encrypt(recipient=recipient, dest_path=file, content=modified)
306814
def pw(
    ctx,
    key_pattern,
    user_pattern,
    mode,
    strict_flag,
    user_flag,
    file,
    edit_subcommand,
    gen_subcommand,
):
    """"""

    # install silent Ctrl-C handler
    def handle_sigint(*_):
        click.echo()
        ctx.exit(1)

    signal.signal(signal.SIGINT, handle_sigint)

    # invoke a subcommand?
    if gen_subcommand:
        length = int(key_pattern) if key_pattern else None
        generate_password(mode, length)
        return
    elif edit_subcommand:
        launch_editor(ctx, file)
        return

    # verify that database file is present
    if not os.path.exists(file):
        click.echo("error: password store not found at '%s'" % file, err=True)
        ctx.exit(1)

    # load database
    store = Store.load(file)

    # if no user query provided, split key query according to right-most "@" sign (since usernames are typically email addresses)
    if not user_pattern:
        user_pattern, _, key_pattern = key_pattern.rpartition("@")

    # search database
    results = store.search(key_pattern, user_pattern)
    results = list(results)

    # if strict flag is enabled, check that precisely a single record was found
    if strict_flag and len(results) != 1:
        click.echo(
            "error: multiple or no records found (but using --strict flag)", err=True
        )
        ctx.exit(2)

    # raw mode?
    if mode == Mode.RAW:
        for entry in results:
            click.echo(entry.user if user_flag else entry.password)
        return

    # print results
    for idx, entry in enumerate(results):
        # start with key and user
        line = highlight_match(key_pattern, entry.key)
        if entry.user:
            line += ": " + highlight_match(user_pattern, entry.user)

        # add password or copy&paste sucess message
        if mode == Mode.ECHO and not user_flag:
            line += " | " + style_password(entry.password)
        elif mode == Mode.COPY and idx == 0:
            try:
                import pyperclip

                pyperclip.copy(entry.user if user_flag else entry.password)
                result = style_success(
                    "*** %s COPIED TO CLIPBOARD ***"
                    % ("USERNAME" if user_flag else "PASSWORD")
                )
            except ImportError:
                result = style_error('*** PYTHON PACKAGE "PYPERCLIP" NOT FOUND ***')
            line += " | " + result

        # add notes
        if entry.notes:
            if idx == 0:
                line += "\n"
                line += "\n".join("   " + line for line in entry.notes.splitlines())
            else:
                lines = entry.notes.splitlines()
                line += " | " + lines[0]
                if len(lines) > 1:
                    line += " (...)"
        click.echo(line)
471055
def cli(env, identifier):
    """"""

    manager = SoftLayer.HardwareManager(env.client)
    hardware_id = helpers.resolve_id(manager.resolve_ids,
                                     identifier,
                                     'hardware')
    instance = manager.get_hardware(hardware_id)

    table = formatting.Table(['username', 'password'])
    for item in instance['softwareComponents']:
        if 'passwords' not in item:
            raise exceptions.SoftLayerError("No passwords found in softwareComponents")
        for credentials in item['passwords']:
            table.add_row([credentials.get('username', 'None'), credentials.get('password', 'None')])
    env.fout(table)
125050
def _decrypt_and_extract(self, fname):
        '''
        
        '''
        with open(fname, "r") as fp_in:
            encrypted_data = fp_in.read()

            decrypted_data = self._hilink_decrypt(encrypted_data)

            with open(binwalk.core.common.unique_file_name(fname[:-4], "dec"), "w") as fp_out:
                fp_out.write(decrypted_data)
1267864
def unlock(password)
      cmd = Xcode::Shell::Command.new "security"
      cmd << "unlock-keychain"
      cmd << "-p #{password}"
      cmd << "\"#{@path}\""
      cmd.execute
    end
410424
def main():
    ''''''
    args = docopt(__doc__, version=__version__)
    if args.get('backup'):
        backup_database(args)
    if args.get('backup_all'):
        backup_all(args)
    if args.get('decrypt'):
        decrypt_file(args.get('<path>'))
    if args.get('configure'):
        configure(service='all')
    if args.get('configure-aws'):
        configure(service='aws')
    if args.get('configure-dropbox'):
        configure(service='dropbox')
    if args.get('configure-swift'):
        configure(service='swift')
    if args.get('download_all'):
        download_all()
212074
def decrypt_file(path, password=None):
    '''
    
    '''
    global PASSWORD_FILE
    if not password:
        password = PASSWORD_FILE
    if path and not os.path.isfile(path):
        raise SystemExit(_error_codes.get(106))
    query = 'openssl aes-128-cbc -d -salt -in {0} -out {1} -k {2}'
    with hide('output'):
        local(query.format(path, path + '.tar.gz', PASSWORD_FILE))
804606
def load(keystorerc=None, keystore=None, copyto=None, verbose=False):
  ''''''

  config = None
  if keystorerc:
    config = config_reader.read(keystorerc)
    if not config:
      print('No configuration found.', file=sys.stderr)
      sys.exit(-1)
  elif keystore:
    config = {
      'keystore': keystore,
      'files': []
    }

  if 'verbose' in config and config['verbose']:
    verbose = True

  keystore_path = None
  if 'keystore' not in config:
    print('.keystorerc needs to specify a keystore file path.', file=sys.stderr)
    sys.exit(-1)
  elif not pathlib.Path(os.path.expanduser(config['keystore'])).is_file():
    # If keystore file does not exist, nothing to load and exits
    print('keystore does not exist: {}'.format(config['keystore']), file=sys.stderr)
    sys.exit(-1)
  else:
    keystore_path = config['keystore']

  if copyto and not pathlib.Path(os.path.expanduser(copyto)).is_dir():
    print('The folder to copy to does not exist: {}'.format(copyto), file=sys.stderr)
    sys.exit(-1)

  # load and attempt to unencrypt keystore by passphrase

  encrypted_keystore = None
  try:
    with open(os.path.expanduser(keystore_path), 'rb') as keystore_file:
      encrypted_keystore = keystore_file.read()

    if verbose: print('Located encrypted keystore at {}.'.format(keystore_path))

    decrypted = False
    decrypted_keystore = None
    while not decrypted:
      try:
        passphrase = getpass.getpass('Please enter the passphrase: ')
        decrypted_keystore = simplecrypt.decrypt(passphrase, encrypted_keystore)
        decrypted = True
      except simplecrypt.DecryptionException as err:
        print('Invalid passphrase. Please try again.')
      except UnicodeDecodeError as err:
        print('Keyring cannot be decrypted.\nError: {}'.format(err), file=sys.stderr)
        sys.exit(-1)

  except OSError as err:
    print('keystore cannot be opened: {}'.format(err), file=sys.stderr)
    sys.exit(-1)

  # attempt to uncompress the keystore

  decompressed_keystore = gzip.decompress(decrypted_keystore)

  # attempt to unserialise the keystore

  try:
    keystore = json.loads(decompressed_keystore)
  except json.decoder.JSONDecodeError as err:
    print('Please contact the author about this as this is a serious problem. {}'.format(err), file=sys.stderr)
    sys.exit(-1)

  if verbose: print('Keystore decrypted successfully.')

  count = 0
  for filepath, key in keystore.items():
    expanded_filepath = os.path.expanduser(filepath)
    if copyto:
      expanded_filepath = os.path.join(copyto, os.path.basename(filepath))

    confirmed = False
    overwrite = False
    if not pathlib.Path(expanded_filepath).exists():
      confirmed = True
      overwrite = True

    while not confirmed:
      overwrite = input('File {} exists. Are you sure you want to overwrite? (y)/n: '.format(expanded_filepath))
      if overwrite == '' or overwrite == 'y' or overwrite == 'Y':
        overwrite = True
        confirmed = True
      elif overwrite == 'n' or overwrite == 'N':
        overwrite = False
        confirmed = True
      else:
        print('Please enter y or n.')
    if not overwrite:
      continue

    # key ready to be created
    if verbose: print('Writing key to {} ...'.format(expanded_filepath))
    try:
      with open(expanded_filepath, 'wb') as keyfile:
        b64_decoded = base64.decodebytes(key.encode('utf-8'))
        keyfile.write(b64_decoded)
      count += 1
    except OSError as err:
      print('File system threw an error: {}'.format(err), file=sys.stderr)
      print('Skipping {}'.format(expanded_filepath))

  if verbose: print('Keystore restored {} keys.'.format(count))
923408
def decrypt(self, enctext, key_file=None, id_attr=''):
        
        if not id_attr:
            id_attr = self.id_attr

        if not isinstance(key_file, list):
            key_file = [key_file]

        key_files = [
            key for key in itertools.chain(key_file, self.enc_key_files) if key
        ]
        for key_file in key_files:
            try:
                dectext = self.crypto.decrypt(enctext, key_file, id_attr)
            except XmlsecError as e:
                continue
            else:
                if dectext:
                    return dectext

        errmsg = "No key was able to decrypt the ciphertext. Keys tried: {keys}"
        errmsg = errmsg.format(keys=key_files)
        raise DecryptError(errmsg)
469329
def perform!(email, password, &block)
      login_required
      CaTissue::Database.current.open(email, password, &block)
    end
1321676
def get_mysql_password_on_disk(self, username=None, password=None):
        """"""
        if username:
            template = self.user_passwd_file_template
            passwd_file = template.format(username)
        else:
            passwd_file = self.root_passwd_file_template

        _password = None
        if os.path.exists(passwd_file):
            log("Using existing password file '%s'" % passwd_file, level=DEBUG)
            with open(passwd_file, 'r') as passwd:
                _password = passwd.read().strip()
        else:
            log("Generating new password file '%s'" % passwd_file, level=DEBUG)
            if not os.path.isdir(os.path.dirname(passwd_file)):
                # NOTE: need to ensure this is not mysql root dir (which needs
                # to be mysql readable)
                mkdir(os.path.dirname(passwd_file), owner='root', group='root',
                      perms=0o770)
                # Force permissions - for some reason the chmod in makedirs
                # fails
                os.chmod(os.path.dirname(passwd_file), 0o770)

            _password = password or pwgen(length=32)
            write_file(passwd_file, _password, owner='root', group='root',
                       perms=0o660)

        return _password
204092
def encrypt_password(self):
        
        if self.password and not self.password.startswith('$pbkdf2'):
            self.set_password(self.password)
950733
def cli(env, username, email, password, from_user, template, api_key):
    

    mgr = SoftLayer.UserManager(env.client)
    user_mask = ("mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, "
                 "state, userStatusId, timezoneId]")
    from_user_id = None
    if from_user is None:
        user_template = mgr.get_current_user(objectmask=user_mask)
        from_user_id = user_template['id']
    else:
        from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
        user_template = mgr.get_user(from_user_id, objectmask=user_mask)
    # If we send the ID back to the API, an exception will be thrown
    del user_template['id']

    if template is not None:
        try:
            template_object = json.loads(template)
            for key in template_object:
                user_template[key] = template_object[key]
        except ValueError as ex:
            raise exceptions.ArgumentError("Unable to parse --template. %s" % ex)

    user_template['username'] = username
    if password == 'generate':
        password = generate_password()

    user_template['email'] = email

    if not env.skip_confirmations:
        table = formatting.KeyValueTable(['name', 'value'])
        for key in user_template:
            table.add_row([key, user_template[key]])
        table.add_row(['password', password])
        click.secho("You are about to create the following user...", fg='green')
        env.fout(table)
        if not formatting.confirm("Do you wish to continue?"):
            raise exceptions.CLIAbort("Canceling creation!")

    result = mgr.create_user(user_template, password)
    new_api_key = None
    if api_key:
        click.secho("Adding API key...", fg='green')
        new_api_key = mgr.add_api_authentication_key(result['id'])

    table = formatting.Table(['Username', 'Email', 'Password', 'API Key'])
    table.add_row([result['username'], result['email'], password, new_api_key])
    env.fout(table)
727541
def _create_login_secret(challenge, password):
        """"""
        to_hash = (challenge + '-' + password).encode('UTF-16LE')
        hashed = hashlib.md5(to_hash).hexdigest()
        return '{0}-{1}'.format(challenge, hashed)
644369
def _run_initdb(name,
        auth='password',
        user=None,
        password=None,
        encoding='UTF8',
        locale=None,
        runas=None,
        waldir=None,
        checksums=False):
    '''
    
    '''
    if runas is None:
        if 'FreeBSD' in __grains__['os_family']:
            runas = 'pgsql'
        elif 'OpenBSD' in __grains__['os_family']:
            runas = '_postgresql'
        else:
            runas = 'postgres'

    if user is None:
        user = runas
    _INITDB_BIN = _find_pg_binary('initdb')
    if not _INITDB_BIN:
        raise CommandExecutionError('initdb executable not found.')
    cmd = [
        _INITDB_BIN,
        '--pgdata={0}'.format(name),
        '--username={0}'.format(user),
        '--auth={0}'.format(auth),
        '--encoding={0}'.format(encoding),
        ]

    if locale is not None:
        cmd.append('--locale={0}'.format(locale))

    # intentionally use short option, as the long option name has been
    # renamed from "xlogdir" to "waldir" in PostgreSQL 10
    if waldir is not None:
        cmd.append('-X')
        cmd.append(waldir)

    if checksums:
        cmd.append('--data-checksums')

    if password is not None:
        pgpassfile = salt.utils.files.mkstemp(text=True)
        with salt.utils.files.fopen(pgpassfile, 'w') as fp_:
            fp_.write(salt.utils.stringutils.to_str('{0}'.format(password)))
            __salt__['file.chown'](pgpassfile, runas, '')
        cmd.extend([
            '--pwfile={0}'.format(pgpassfile),
        ])

    kwargs = dict(runas=runas, clean_env=True)
    cmdstr = ' '.join([pipes.quote(c) for c in cmd])
    ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs)

    if ret.get('retcode', 0) != 0:
        log.error('Error initilizing the postgres data directory')

    if password is not None and not __salt__['file.remove'](pgpassfile):
        log.warning('Removal of PGPASSFILE failed')

    return ret
951485
def enable_mesos_basic_authentication(principal, password):
    
    restart = False
    secrets_file = '/etc/mesos/secrets'
    secrets_entry = '%s %s' % (principal, password)
    if not file_contains(filename=secrets_file,
                         text=secrets_entry, use_sudo=True):
        file_append(filename=secrets_file, text=secrets_entry, use_sudo=True)
        file_attribs(secrets_file, mode=700, sudo=True)
        restart = True

    # set new startup parameters for mesos-master
    with quiet():
        if secrets_file not in sudo('cat /etc/mesos-master/credentials'):
            sudo('echo %s > /etc/mesos-master/credentials' % secrets_file)
            restart = True

        if not exists('/etc/mesos-master/\?authenticate', use_sudo=True):
            sudo('touch /etc/mesos-master/\?authenticate')
            file_attribs('/etc/mesos-master/\?authenticate',
                         mode=700,
                         sudo=True)
            restart = True

    if restart:
        restart_service('mesos-master')
803295
function exec(script, numkeys) {
  var KEYS = slice.call(arguments, 2, 2 + numkeys);
  var ARGS = slice.call(arguments, numkeys + 2);

  function cb(err, reply) {
    if(err) reply = err.message;
    process.send(
      {
        err: (err instanceof Error),
        data: reply,
        str: (reply instanceof String)
    });
  }

  var redis = {
    sha1hex: sha1hex,
    error_reply: function(err) {
      return new Error(err)
    },
    status_reply: function(status) {
      return new String(status)
    },
    call: function(cmd) {
      //console.dir('calling out with: ' + cmd);
      var args = slice.call(arguments, 1)
        , callback = typeof args[args.length - 1] === 'function'
          ? args.pop() : null;

      function onMessage(msg) {
        if(cb) {
          if(msg.err) return cb(new Error(msg.data));
          cb(null, msg.data);
        }
      }
      process.once('message', onMessage);
      process.send({event: 'call', cmd: cmd, args: args});
      return callback || cb;
    },
    LOG_DEBUG: logger.DEBUG,
    LOG_VERBOSE: logger.VERBOSE,
    LOG_NOTICE: logger.NOTICE,
    LOG_WARNING: logger.WARNING,
    log: function rlog() {
      return log.log.apply(log, arguments);
    }
  }

  //console.dir(redis);

  var sandbox = {
    Error: Error,
    Buffer: Buffer,
    JSON: JSON,
    crypto: crypto,
    util: util,
    redis: redis,
    KEYS: KEYS,
    ARGS: ARGS,
    cb: cb
  }

  script.runInNewContext(sandbox);

  process.send({event: 'eval', data: sandbox.method.name});

  var result;
  try {
    result = sandbox.method(sandbox.KEYS, sandbox.ARGS, sandbox.cb);
  // coerce thrown errors
  }catch(e) {
    result = e;
  }

  //console.dir(result);
  if(Buffer.isBuffer(result)) {
    result = result.toString();
  }

  if(result
    && !(result instanceof Error)
    && typeof result === 'object') {
    if(result.err) {
      result = new Error(result.err);
    }else if(result.ok) {
      result = new String(result.ok);
    }
  }

  //console.dir(result);
  return {
    result: result,
    sandbox: sandbox,
    script: script,
    name: sandbox.method.name
  };
}