/**
   * Delete a Role form User.
   *
   * @param username
   * @param role
   */
  public void deleteRole(String username, String role) {
    String[] infos = null;
    StringBuffer userInfoBuffer = new StringBuffer();

    String userInfos = (String) users.get(username);

    // If user already exists, remove the role
    if (userInfos != null && userInfos.length() > 0) {
      infos = userInfos.split(",");
      String password = infos[0];
      userInfoBuffer.append(password);

      for (int i = 1; i < infos.length; i++) {
        if (infos[i] != null && !infos[i].equals(role)) {
          userInfoBuffer.append(",");
          userInfoBuffer.append(infos[i]);
        }
      }
      String newUserInfo = userInfoBuffer.toString();
      users.put(username, newUserInfo);
    }

    try {
      users.save();
    } catch (Exception ex) {
      LOGGER.error("Cannot update users file,", ex);
    }
  }
 private void updateProperty(
     String key, Map<String, String> updatedProperties, Properties systemDotProperties) {
   if (updatedProperties.containsKey(key)) {
     String value = updatedProperties.get(key);
     systemDotProperties.put(key, value);
     System.setProperty(key, value);
   }
 }
Exemple #3
0
 private void markCreated(BundleContext bundleContext) throws IOException {
   File marker = new File(dataDir, ENSEMBLE_MARKER);
   if (!marker.exists() && !marker.getParentFile().exists() && !marker.getParentFile().mkdirs()) {
     throw new IOException("Cannot create marker file");
   }
   org.apache.felix.utils.properties.Properties props =
       new org.apache.felix.utils.properties.Properties(marker);
   props.put("created", "true");
   props.save();
 }
 /**
  * Add a role to a User.
  *
  * @param username
  * @param role
  */
 public void addRole(String username, String role) {
   String userInfos = (String) users.get(username);
   if (userInfos != null) {
     String newUserInfos = userInfos + "," + role;
     users.put(username, newUserInfos);
   }
   try {
     users.save();
   } catch (Exception ex) {
     LOGGER.error("Cannot update users file,", ex);
   }
 }
  /**
   * Add a user.
   *
   * @param username
   * @param password
   */
  public void addUser(String username, String password) {
    String[] infos = null;
    StringBuffer userInfoBuffer = new StringBuffer();

    String newPassword = password;

    // If encryption support is enabled, encrypt password
    if (encryptionSupport != null && encryptionSupport.getEncryption() != null) {
      newPassword = encryptionSupport.getEncryption().encryptPassword(password);
      if (encryptionSupport.getEncryptionPrefix() != null) {
        newPassword = encryptionSupport.getEncryptionPrefix() + newPassword;
      }
      if (encryptionSupport.getEncryptionSuffix() != null) {
        newPassword = newPassword + encryptionSupport.getEncryptionSuffix();
      }
    }

    String userInfos = (String) users.get(username);

    // If user already exists, update password
    if (userInfos != null && userInfos.length() > 0) {
      infos = userInfos.split(",");
      userInfoBuffer.append(newPassword);

      for (int i = 1; i < infos.length; i++) {
        userInfoBuffer.append(",");
        userInfoBuffer.append(infos[i]);
      }
      String newUserInfo = userInfoBuffer.toString();
      users.put(username, newUserInfo);
    } else {
      users.put(username, newPassword);
    }

    try {
      users.save();
    } catch (Exception ex) {
      LOGGER.error("Cannot update users file,", ex);
    }
  }
Exemple #6
0
  void configureInternal(Map<String, ?> conf) throws Exception {
    configuration = configurer.configure(conf, this);

    if (Strings.isNullOrBlank(runtimeId)) {
      throw new IllegalArgumentException("Runtime id must not be null or empty.");
    }

    if (Strings.isNullOrBlank(localResolver)) {
      localResolver = globalResolver;
    }

    String decodedZookeeperPassword = null;

    Properties userProps = new Properties();
    try {
      userProps.load(new File(confDir, "users.properties"));
    } catch (IOException e) {
      LOGGER.warn("Failed to load users from etc/users.properties. No users will be imported.", e);
    }

    if (Strings.isNotBlank(zookeeperPassword)) {
      decodedZookeeperPassword = PasswordEncoder.decode(zookeeperPassword);
    } else if (userProps.containsKey(DEFAULT_ADMIN_USER)) {
      String passwordAndRole = userProps.getProperty(DEFAULT_ADMIN_USER).trim();
      decodedZookeeperPassword =
          passwordAndRole.substring(0, passwordAndRole.indexOf(ROLE_DELIMITER));
    } else {
      decodedZookeeperPassword = PasswordEncoder.encode(CreateEnsembleOptions.generatePassword());
    }

    if (userProps.isEmpty()) {
      userProps.put(
          DEFAULT_ADMIN_USER, decodedZookeeperPassword + ROLE_DELIMITER + DEFAULT_ADMIN_ROLE);
    }

    options =
        CreateEnsembleOptions.builder()
            .bindAddress(bindAddress)
            .agentEnabled(agentAutoStart)
            .ensembleStart(ensembleAutoStart)
            .zookeeperPassword(decodedZookeeperPassword)
            .zooKeeperServerPort(zookeeperServerPort)
            .zooKeeperServerConnectionPort(zookeeperServerConnectionPort)
            .autoImportEnabled(profilesAutoImport)
            .importPath(profilesAutoImportPath)
            .resolver(localResolver)
            .globalResolver(globalResolver)
            .users(userProps)
            .profiles(profiles)
            .version(version)
            .build();
  }
  public void createLocalServer(int port, CreateEnsembleOptions options) {
    try {
      IZKClient client;
      Hashtable<String, Object> properties;
      String version = ZkDefs.DEFAULT_VERSION;
      String karafName = System.getProperty(SystemProperties.KARAF_NAME);
      String minimumPort = System.getProperty(ZkDefs.MINIMUM_PORT);
      String maximumPort = System.getProperty(ZkDefs.MAXIMUM_PORT);
      int mappedPort = mapPortToRange(port, minimumPort, maximumPort);

      if (options.getZookeeperPassword() != null) {
        // do nothing
      } else if (System.getProperties().containsKey(SystemProperties.ZOOKEEPER_PASSWORD)) {
        options.setZookeeperPassword(System.getProperty(SystemProperties.ZOOKEEPER_PASSWORD));
      } else {
        options.setZookeeperPassword(ZooKeeperRetriableUtils.generatePassword());
      }

      // Install or stop the fabric-configadmin bridge
      Bundle bundleFabricAgent =
          findAndStopBundle(bundleContext, "org.fusesource.fabric.fabric-agent");
      Bundle bundleFabricConfigAdmin =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-configadmin",
              "mvn:org.fusesource.fabric/fabric-configadmin/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricZooKeeper =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-zookeeper",
              "mvn:org.fusesource.fabric/fabric-zookeeper/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricJaas =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-jaas  ",
              "mvn:org.fusesource.fabric/fabric-jaas/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricCommands =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-commands  ",
              "mvn:org.fusesource.fabric/fabric-commands/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricMavenProxy =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-commands  ",
              "mvn:org.fusesource.fabric/fabric-maven-proxy/" + FabricConstants.FABRIC_VERSION);

      // Create configuration
      String connectionUrl = HostUtils.getLocalHostName() + ":" + Integer.toString(mappedPort);

      String autoImportFrom = System.getProperty(SystemProperties.PROFILES_AUTOIMPORT_PATH);

      Configuration config =
          configurationAdmin.createFactoryConfiguration("org.fusesource.fabric.zookeeper.server");
      properties = new Hashtable<String, Object>();
      if (autoImportFrom != null) {
        loadPropertiesFrom(
            properties,
            autoImportFrom
                + "/fabric/configs/versions/1.0/profiles/default/org.fusesource.fabric.zookeeper.server.properties");
      }
      properties.put("tickTime", "2000");
      properties.put("initLimit", "10");
      properties.put("syncLimit", "5");
      properties.put("dataDir", "data/zookeeper/0000");
      properties.put("clientPort", Integer.toString(mappedPort));
      properties.put("fabric.zookeeper.pid", "org.fusesource.fabric.zookeeper.server-0000");
      config.setBundleLocation(null);
      config.update(properties);

      // Update the client configuration
      config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper");
      properties = new Hashtable<String, Object>();
      if (autoImportFrom != null) {
        loadPropertiesFrom(
            properties,
            autoImportFrom
                + "/fabric/configs/versions/1.0/profiles/default/org.fusesource.fabric.zookeeper.properties");
      }
      properties.put("zookeeper.url", connectionUrl);
      properties.put(
          "zookeeper.timeout",
          System.getProperties().containsKey("zookeeper.timeout")
              ? System.getProperties().getProperty("zookeeper.timeout")
              : "30000");
      properties.put("fabric.zookeeper.pid", "org.fusesource.fabric.zookeeper");
      properties.put("zookeeper.password", options.getZookeeperPassword());
      config.setBundleLocation(null);
      config.update(properties);

      // Start fabric-zookeeper bundle
      bundleFabricZooKeeper.start();

      // Wait for the client to be available
      ServiceTracker tracker = new ServiceTracker(bundleContext, IZKClient.class.getName(), null);
      tracker.open();
      client = (IZKClient) tracker.waitForService(5000);
      if (client == null) {
        throw new IllegalStateException("Timeout waiting for ZooKeeper client to be registered");
      }
      tracker.close();
      client.waitForConnected();

      // Import data into zookeeper
      if (autoImportFrom != null) {
        getDataStore().importFromFileSystem(autoImportFrom);
      }

      getDataStore().setDefaultVersion(version);

      // configure default profile
      String defaultProfile = getDataStore().getProfile(version, "default", true);

      ZooKeeperRetriableUtils.set(
          client,
          ZkPath.CONFIG_ENSEMBLE_URL.getPath(),
          "${zk:" + karafName + "/ip}:" + Integer.toString(mappedPort));
      ZooKeeperRetriableUtils.set(
          client, ZkPath.CONFIG_ENSEMBLE_PASSWORD.getPath(), options.getZookeeperPassword());

      Properties zkProps = new Properties();
      zkProps.setProperty("zookeeper.url", "${zk:" + ZkPath.CONFIG_ENSEMBLE_URL.getPath() + "}");
      zkProps.setProperty(
          "zookeeper.password", "${zk:" + ZkPath.CONFIG_ENSEMBLE_PASSWORD.getPath() + "}");
      getDataStore()
          .setFileConfiguration(
              version,
              defaultProfile,
              "org.fusesource.fabric.zookeeper.properties",
              DataStoreHelpers.toBytes(zkProps));

      // configure the ensemble
      String ensembleProfile = getDataStore().getProfile(version, "fabric-ensemble-0000", true);
      getDataStore().setProfileAttribute(version, ensembleProfile, "abstract", "true");
      getDataStore().setProfileAttribute(version, ensembleProfile, "hidden", "true");

      Properties ensembleProps = new Properties();
      ensembleProps.put("tickTime", "2000");
      ensembleProps.put("initLimit", "10");
      ensembleProps.put("syncLimit", "5");
      ensembleProps.put("dataDir", "data/zookeeper/0000");

      loadPropertiesFrom(
          ensembleProps,
          autoImportFrom
              + "/fabric/configs/versions/1.0/profiles/default/org.fusesource.fabric.zookeeper.server.properties");
      getDataStore()
          .setFileConfiguration(
              version,
              ensembleProfile,
              "org.fusesource.fabric.zookeeper.server-0000.properties",
              DataStoreHelpers.toBytes(ensembleProps));

      // configure this server in the ensemble
      String ensembleServerProfile =
          getDataStore().getProfile(version, "fabric-ensemble-0000-1", true);
      getDataStore().setProfileAttribute(version, ensembleServerProfile, "hidden", "true");
      getDataStore()
          .setProfileAttribute(version, ensembleServerProfile, "parents", ensembleProfile);
      Properties serverProps = new Properties();
      serverProps.put("clientPort", String.valueOf(mappedPort));
      getDataStore()
          .setFileConfiguration(
              version,
              ensembleServerProfile,
              "org.fusesource.fabric.zookeeper.server-0000.properties",
              DataStoreHelpers.toBytes(serverProps));

      ZooKeeperRetriableUtils.set(client, ZkPath.CONFIG_ENSEMBLES.getPath(), "0000");
      ZooKeeperRetriableUtils.set(client, ZkPath.CONFIG_ENSEMBLE.getPath("0000"), karafName);

      // configure fabric profile
      String fabricProfile = getDataStore().getProfile(version, "fabric", true);
      Properties agentProps =
          DataStoreHelpers.toProperties(
              getDataStore()
                  .getFileConfiguration(
                      version, fabricProfile, "org.fusesource.fabric.agent.properties"));
      agentProps.put("feature.fabric-commands", "fabric-commands");
      getDataStore()
          .setFileConfiguration(
              version,
              "fabric",
              "org.fusesource.fabric.agent.properties",
              DataStoreHelpers.toBytes(agentProps));

      ZooKeeperRetriableUtils.createDefault(
          client, ZkPath.CONFIG_CONTAINER.getPath(karafName), version);
      String assignedProfile = System.getProperty(SystemProperties.PROFILE);
      if (assignedProfile != null
          && !assignedProfile.isEmpty()
          && !"fabric".equals(assignedProfile)) {
        ZooKeeperRetriableUtils.createDefault(
            client,
            ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, karafName),
            "fabric fabric-ensemble-0000-1 " + assignedProfile);
      } else {
        ZooKeeperRetriableUtils.createDefault(
            client,
            ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, karafName),
            "fabric fabric-ensemble-0000-1");
      }

      // add auth
      Map<String, String> configs = new HashMap<String, String>();
      configs.put("encryption.enabled", "${zk:/fabric/authentication/encryption.enabled}");
      getDataStore()
          .setConfiguration(version, defaultProfile, "org.fusesource.fabric.jaas", configs);

      // outside of the profile storage area, so we'll keep these in zk
      ZooKeeperRetriableUtils.createDefault(
          client, "/fabric/authentication/encryption.enabled", "true");
      ZooKeeperRetriableUtils.createDefault(client, "/fabric/authentication/domain", "karaf");
      addUsersToZookeeper(client, options.getUsers());

      ZooKeeperRetriableUtils.createDefault(
          client, ZkPath.AUTHENTICATION_CRYPT_ALGORITHM.getPath(), "PBEWithMD5AndDES");
      ZooKeeperRetriableUtils.createDefault(
          client, ZkPath.AUTHENTICATION_CRYPT_PASSWORD.getPath(), options.getZookeeperPassword());

      // Fix acls
      ZookeeperCommandBuilder.fixAcls("/", true).execute(client);

      // Reset the autostart flag
      if (ensembleAutoStart) {
        System.setProperty(SystemProperties.ENSEMBLE_AUTOSTART, Boolean.FALSE.toString());
        File file = new File(System.getProperty("karaf.base") + "/etc/system.properties");
        org.apache.felix.utils.properties.Properties props =
            new org.apache.felix.utils.properties.Properties(file);
        props.put(SystemProperties.ENSEMBLE_AUTOSTART, Boolean.FALSE.toString());
        props.save();
      }

      // Restart fabric-configadmin bridge
      bundleFabricConfigAdmin.start();
      bundleFabricJaas.start();
      bundleFabricCommands.start();
      bundleFabricMavenProxy.start();

      // Check if the agent is configured to auto start.
      if (!System.getProperties().containsKey(SystemProperties.AGENT_AUTOSTART)
          || Boolean.parseBoolean(System.getProperty(SystemProperties.AGENT_AUTOSTART))) {
        bundleFabricAgent =
            findOrInstallBundle(
                bundleContext,
                "org.fusesource.fabric.fabric-agent  ",
                "mvn:org.fusesource.fabric/fabric-agent/" + FabricConstants.FABRIC_VERSION);
        bundleFabricAgent.start();
      }
    } catch (Exception e) {
      throw new FabricException("Unable to create zookeeper server configuration", e);
    }
  }
  public boolean login() throws LoginException {
    File f = new File(usersFile);
    Properties users;
    try {
      users = new Properties(f);
    } catch (IOException ioe) {
      throw new LoginException("Unable to load user properties file " + f);
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: "******" not available to obtain information from user");
    }
    String user = ((NameCallback) callbacks[0]).getName();
    if (user == null) {
      throw new FailedLoginException("Unable to retrieve user name");
    }
    PublicKey key = ((PublickeyCallback) callbacks[1]).getPublicKey();
    if (key == null) {
      throw new FailedLoginException("Unable to retrieve public key");
    }

    // user infos container read from the users properties file
    String userInfos = null;

    try {
      userInfos = (String) users.get(user);
    } catch (NullPointerException e) {
      // error handled in the next statement
    }
    if (userInfos == null) {
      if (!this.detailedLoginExcepion) {
        throw new FailedLoginException("login failed");
      } else {
        throw new FailedLoginException("User " + user + " does not exist");
      }
    }

    // the password is in the first position
    String[] infos = userInfos.split(",");
    String storedKey = infos[0];

    // check if the stored password is flagged as encrypted
    String encryptedKey = getEncryptedPassword(storedKey);
    if (!storedKey.equals(encryptedKey)) {
      if (debug) {
        LOG.debug("The key isn't flagged as encrypted, encrypt it.");
      }
      if (debug) {
        LOG.debug("Rebuild the user informations string.");
      }
      userInfos = encryptedKey + ",";
      for (int i = 2; i < infos.length; i++) {
        if (i == (infos.length - 1)) {
          userInfos = userInfos + infos[i];
        } else {
          userInfos = userInfos + infos[i] + ",";
        }
      }
      if (debug) {
        LOG.debug("Push back the user informations in the users properties.");
      }
      users.put(user, userInfos);
      try {
        if (debug) {
          LOG.debug("Store the users properties file.");
        }
        users.save();
      } catch (IOException ioe) {
        LOG.warn("Unable to write user properties file " + f, ioe);
      }
      storedKey = encryptedKey;
    }

    // check the provided password
    if (!checkPassword(getString(key), storedKey)) {
      if (!this.detailedLoginExcepion) {
        throw new FailedLoginException("login failed");
      } else {
        throw new FailedLoginException("Public key for " + user + " does not match");
      }
    }

    principals = new HashSet<Principal>();
    principals.add(new UserPrincipal(user));
    for (int i = 1; i < infos.length; i++) {
      principals.add(new RolePrincipal(infos[i]));
    }

    users.clear();

    if (debug) {
      LOG.debug("Successfully logged in " + user);
    }
    return true;
  }