List of usage examples for org.apache.commons.codec.digest DigestUtils sha1Hex
public static String sha1Hex(String data)
From source file:no.asgari.civilization.server.action.PlayerAction.java
public void newPassword(String username, String newPass) throws Exception { Player player = playerCollection.findOne(DBQuery.is(Player.USERNAME, username)); if (player == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); }//w ww. j ava 2 s . co m String password = URLDecoder.decode(newPass, "UTF-8"); player.setPassword(DigestUtils.sha1Hex(password)); playerCollection.updateById(player.getId(), player); }
From source file:no.asgari.civilization.server.action.PlayerAction.java
public boolean verifyPassword(String playerId) { Player player = playerCollection.findOneById(playerId); if (player != null && !Strings.isNullOrEmpty(player.getNewPassword())) { try {//w ww . ja v a2 s. com String password = URLDecoder.decode(player.getNewPassword(), "UTF-8"); player.setPassword(DigestUtils.sha1Hex(password)); player.setNewPassword(null); playerCollection.updateById(player.getId(), player); return true; } catch (UnsupportedEncodingException e) { log.error("Couldn't write password ", e); throw new WebApplicationException(Response.Status.BAD_REQUEST); } } return false; }
From source file:no.asgari.civilization.server.application.CivAuthenticator.java
@Override public Optional<Player> authenticate(BasicCredentials credentials) { @Cleanup//from w w w .j a v a2s .c om DBCursor<Player> dbPlayer = playerCollection.find(DBQuery.is("username", credentials.getUsername()), new BasicDBObject()); if (dbPlayer == null || !dbPlayer.hasNext()) { return Optional.empty(); } Player player = dbPlayer.next(); CivSingleton.instance().playerCache().put(player.getId(), player.getUsername()); if (player.getPassword().equals(DigestUtils.sha1Hex(credentials.getPassword()))) { return Optional.of(player); } return Optional.empty(); }
From source file:org.ancoron.hazelcast.rest.osgi.HazelcastServiceTest.java
@Test public void lifecycleSimple() throws Exception { Config cfg = new Config("HazelcastServiceTest"); // disable multicast... cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); HazelcastMapServlet service = new HazelcastMapServlet(); service.setHazelcast(hz);//ww w .j av a 2 s. c om // Step #1: create a bucket service.createBucket("A", 60, 0, 128); // Step #2: insert some data for a key MessageDigest md5 = DigestUtils.getMd5Digest(); MessageDigest sha1 = DigestUtils.getSha1Digest(); try (InputStream testData = new DigestInputStream(new DigestInputStream(stream("test.json"), sha1), md5)) { service.setValue("A", "1", "application/json", 171, testData); } // Step #3: fetch some data for a key byte[] value = service.getValue("A", "1"); byte[] data = new byte[value.length - 1]; System.arraycopy(value, 1, data, 0, data.length); Assert.assertThat(DigestUtils.md5Hex(data), CoreMatchers.is(Hex.encodeHexString(md5.digest()))); Assert.assertThat(DigestUtils.sha1Hex(data), CoreMatchers.is(Hex.encodeHexString(sha1.digest()))); // Step #4: delete the bucket service.deleteBucket("A"); }
From source file:org.apache.accumulo.tserver.DirectoryDecommissioner.java
private static String hash(FileSystem fs, Path dir, String name) throws IOException { FSDataInputStream in = fs.open(new Path(dir, name)); try {/* w w w .jav a 2 s.com*/ return DigestUtils.sha1Hex(in); } finally { in.close(); } }
From source file:org.apache.ambari.server.agent.HeartBeatHandler.java
/** * Insert Kerberos keytab details into the ExecutionCommand for the SET_KEYTAB custom command if * any keytab details and associated data exists for the target host. * * @param ec the ExecutionCommand to update * @param command a name of the relevant keytab command * @param targetHost a name of the host the relevant command is destined for * @throws AmbariException//www.ja v a2s .c o m */ void injectKeytab(ExecutionCommand ec, String command, String targetHost) throws AmbariException { List<Map<String, String>> kcp = ec.getKerberosCommandParams(); String dataDir = ec.getCommandParams().get(KerberosServerAction.DATA_DIRECTORY); KerberosActionDataFileReader reader = null; try { reader = new KerberosActionDataFileReader(new File(dataDir, KerberosActionDataFile.DATA_FILE_NAME)); for (Map<String, String> record : reader) { String hostName = record.get(KerberosActionDataFile.HOSTNAME); if (targetHost.equalsIgnoreCase(hostName)) { if ("SET_KEYTAB".equalsIgnoreCase(command)) { String keytabFilePath = record.get(KerberosActionDataFile.KEYTAB_FILE_PATH); if (keytabFilePath != null) { String sha1Keytab = DigestUtils.sha1Hex(keytabFilePath); File keytabFile = new File( dataDir + File.separator + hostName + File.separator + sha1Keytab); if (keytabFile.canRead()) { Map<String, String> keytabMap = new HashMap<String, String>(); String principal = record.get(KerberosActionDataFile.PRINCIPAL); String isService = record.get(KerberosActionDataFile.SERVICE); keytabMap.put(KerberosActionDataFile.HOSTNAME, hostName); keytabMap.put(KerberosActionDataFile.SERVICE, isService); keytabMap.put(KerberosActionDataFile.COMPONENT, record.get(KerberosActionDataFile.COMPONENT)); keytabMap.put(KerberosActionDataFile.PRINCIPAL, principal); keytabMap.put(KerberosActionDataFile.PRINCIPAL_CONFIGURATION, record.get(KerberosActionDataFile.PRINCIPAL_CONFIGURATION)); keytabMap.put(KerberosActionDataFile.KEYTAB_FILE_PATH, keytabFilePath); keytabMap.put(KerberosActionDataFile.KEYTAB_FILE_OWNER_NAME, record.get(KerberosActionDataFile.KEYTAB_FILE_OWNER_NAME)); keytabMap.put(KerberosActionDataFile.KEYTAB_FILE_OWNER_ACCESS, record.get(KerberosActionDataFile.KEYTAB_FILE_OWNER_ACCESS)); keytabMap.put(KerberosActionDataFile.KEYTAB_FILE_GROUP_NAME, record.get(KerberosActionDataFile.KEYTAB_FILE_GROUP_NAME)); keytabMap.put(KerberosActionDataFile.KEYTAB_FILE_GROUP_ACCESS, record.get(KerberosActionDataFile.KEYTAB_FILE_GROUP_ACCESS)); keytabMap.put(KerberosActionDataFile.KEYTAB_FILE_CONFIGURATION, record.get(KerberosActionDataFile.KEYTAB_FILE_CONFIGURATION)); BufferedInputStream bufferedIn = new BufferedInputStream( new FileInputStream(keytabFile)); byte[] keytabContent = IOUtils.toByteArray(bufferedIn); String keytabContentBase64 = Base64.encodeBase64String(keytabContent); keytabMap.put(KerberosServerAction.KEYTAB_CONTENT_BASE64, keytabContentBase64); kcp.add(keytabMap); } } } else if ("REMOVE_KEYTAB".equalsIgnoreCase(command)) { Map<String, String> keytabMap = new HashMap<String, String>(); keytabMap.put(KerberosActionDataFile.HOSTNAME, hostName); keytabMap.put(KerberosActionDataFile.SERVICE, record.get(KerberosActionDataFile.SERVICE)); keytabMap.put(KerberosActionDataFile.COMPONENT, record.get(KerberosActionDataFile.COMPONENT)); keytabMap.put(KerberosActionDataFile.PRINCIPAL, record.get(KerberosActionDataFile.PRINCIPAL)); keytabMap.put(KerberosActionDataFile.KEYTAB_FILE_PATH, record.get(KerberosActionDataFile.KEYTAB_FILE_PATH)); kcp.add(keytabMap); } } } } catch (IOException e) { throw new AmbariException("Could not inject keytabs to enable kerberos"); } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { // ignored } } } ec.setKerberosCommandParams(kcp); }
From source file:org.apache.ambari.server.agent.TestHeartbeatHandler.java
private File createTestKeytabData() throws Exception { File dataDirectory = temporaryFolder.newFolder(); File indexFile = new File(dataDirectory, KerberosActionDataFile.DATA_FILE_NAME); KerberosActionDataFileBuilder kerberosActionDataFileBuilder = new KerberosActionDataFileBuilder(indexFile); File hostDirectory = new File(dataDirectory, "c6403.ambari.apache.org"); File keytabFile;//from w ww . j ava 2s . com if (hostDirectory.mkdirs()) keytabFile = new File(hostDirectory, DigestUtils.sha1Hex("/etc/security/keytabs/dn.service.keytab")); else throw new Exception("Failed to create " + hostDirectory.getAbsolutePath()); kerberosActionDataFileBuilder.addRecord("c6403.ambari.apache.org", "HDFS", "DATANODE", "dn/_HOST@_REALM", "service", "hdfs-site/dfs.namenode.kerberos.principal", "/etc/security/keytabs/dn.service.keytab", "hdfs", "r", "hadoop", "", "hdfs-site/dfs.namenode.keytab.file", "false"); kerberosActionDataFileBuilder.close(); // Ensure the host directory exists... FileWriter fw = new FileWriter(keytabFile); BufferedWriter bw = new BufferedWriter(fw); bw.write("hello"); bw.close(); return dataDirectory; }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Creates a new principal in a previously configured KDC * <p/>/* w ww. ja va 2 s .c om*/ * The implementation is specific to a particular type of KDC. * * @param principal a String containing the principal to add * @param password a String containing the password to use when creating the principal * @param service a boolean value indicating whether the principal is to be created as a service principal or not * @return an Integer declaring the generated key number * @throws KerberosOperationException */ @Override public Integer createPrincipal(String principal, String password, boolean service) throws KerberosOperationException { if (!isOpen()) { throw new KerberosOperationException("This operation handler has not been opened"); } if (principal == null) { throw new KerberosOperationException("principal is null"); } if (password == null) { throw new KerberosOperationException("principal password is null"); } DeconstructedPrincipal deconstructedPrincipal = createDeconstructPrincipal(principal); String realm = deconstructedPrincipal.getRealm(); if (realm == null) { realm = ""; } Map<String, Object> context = new HashMap<String, Object>(); context.put("normalized_principal", deconstructedPrincipal.getNormalizedPrincipal()); context.put("principal_name", deconstructedPrincipal.getPrincipalName()); context.put("principal_primary", deconstructedPrincipal.getPrimary()); context.put("principal_instance", deconstructedPrincipal.getInstance()); context.put("realm", realm); context.put("realm_lowercase", realm.toLowerCase()); context.put("password", password); context.put("is_service", service); context.put("container_dn", this.principalContainerDn); context.put("principal_digest", DigestUtils.sha1Hex(deconstructedPrincipal.getNormalizedPrincipal())); Map<String, Object> data = processCreateTemplate(context); Attributes attributes = new BasicAttributes(); String cn = null; if (data != null) { for (Map.Entry<String, Object> entry : data.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if ("unicodePwd".equals(key)) { if (value instanceof String) { try { attributes.put(new BasicAttribute("unicodePwd", String.format("\"%s\"", password).getBytes("UTF-16LE"))); } catch (UnsupportedEncodingException ue) { throw new KerberosOperationException("Can not encode password with UTF-16LE", ue); } } } else { Attribute attribute = new BasicAttribute(key); if (value instanceof Collection) { for (Object object : (Collection) value) { attribute.add(object); } } else { attribute.add(value); if ("cn".equals(key) && (value != null)) { cn = value.toString(); } } attributes.put(attribute); } } } if (cn == null) { cn = deconstructedPrincipal.getNormalizedPrincipal(); } try { Name name = new CompositeName().add(String.format("cn=%s,%s", cn, principalContainerDn)); ldapContext.createSubcontext(name, attributes); } catch (NamingException ne) { throw new KerberosOperationException("Can not create principal : " + principal, ne); } return 0; }
From source file:org.apache.ambari.server.serveraction.kerberos.CreateKeytabFilesServerAction.java
/** * For each identity, create a keytab and append to a new or existing keytab file. * <p/>//from w w w . j a v a2 s . com * It is expected that the {@link org.apache.ambari.server.serveraction.kerberos.CreatePrincipalsServerAction} * (or similar) has executed before this action and a set of passwords has been created, map to * their relevant (evaluated) principals and stored in the requestSharedDataContext. * <p/> * If a password exists for the current evaluatedPrincipal, use a * {@link org.apache.ambari.server.serveraction.kerberos.KerberosOperationHandler} to generate * the keytab file. To help avoid filename collisions and to build a structure that is easy to * discover, each keytab file is stored in host-specific * ({@link org.apache.ambari.server.serveraction.kerberos.KerberosActionDataFile#HOSTNAME}) * directory using the SHA1 hash of its destination file path * ({@link org.apache.ambari.server.serveraction.kerberos.KerberosActionDataFile#KEYTAB_FILE_PATH}) * <p/> * <pre> * data_directory * |- host1 * | |- 16a054404c8826cd604a27ac970e8cc4b9c7a3fa (keytab file) * | |- ... (keytab files) * | |- a3c09cae73406912e8c55296d1c85b674d24f576 (keytab file) * |- host2 * | |- ... * </pre> * * @param identityRecord a Map containing the data for the current identity record * @param evaluatedPrincipal a String indicating the relevant principal * @param operationHandler a KerberosOperationHandler used to perform Kerberos-related * tasks for specific Kerberos implementations * (MIT, Active Directory, etc...) * @param requestSharedDataContext a Map to be used a shared data among all ServerActions related * to a given request * @return a CommandReport, indicating an error condition; or null, indicating a success condition * @throws AmbariException if an error occurs while processing the identity record */ @Override protected CommandReport processIdentity(Map<String, String> identityRecord, String evaluatedPrincipal, KerberosOperationHandler operationHandler, Map<String, Object> requestSharedDataContext) throws AmbariException { CommandReport commandReport = null; if (identityRecord != null) { String message; if (operationHandler == null) { message = String.format("Failed to create keytab file for %s, missing KerberosOperationHandler", evaluatedPrincipal); actionLog.writeStdErr(message); LOG.error(message); commandReport = createCommandReport(1, HostRoleStatus.FAILED, "{}", actionLog.getStdOut(), actionLog.getStdErr()); } else { Map<String, String> principalPasswordMap = getPrincipalPasswordMap(requestSharedDataContext); Map<String, Integer> principalKeyNumberMap = getPrincipalKeyNumberMap(requestSharedDataContext); String host = identityRecord.get(HOSTNAME); String keytabFilePath = identityRecord.get(KEYTAB_FILE_PATH); if ((host != null) && !host.isEmpty() && (keytabFilePath != null) && !keytabFilePath.isEmpty()) { Set<String> visitedPrincipalKeys = visitedIdentities.get(evaluatedPrincipal); String visitationKey = String.format("%s|%s", host, keytabFilePath); if ((visitedPrincipalKeys == null) || !visitedPrincipalKeys.contains(visitationKey)) { // Look up the current evaluatedPrincipal's password. // If found create the keytab file, else try to find it in the cache. String password = principalPasswordMap.get(evaluatedPrincipal); message = String.format("Creating keytab file for %s on host %s", evaluatedPrincipal, host); LOG.info(message); actionLog.writeStdOut(message); // Determine where to store the keytab file. It should go into a host-specific // directory under the previously determined data directory. File hostDirectory = new File(getDataDirectoryPath(), host); // Ensure the host directory exists... if (!hostDirectory.exists() && hostDirectory.mkdirs()) { // Make sure only Ambari has access to this directory. ensureAmbariOnlyAccess(hostDirectory); } if (hostDirectory.exists()) { File destinationKeytabFile = new File(hostDirectory, DigestUtils.sha1Hex(keytabFilePath)); if (password == null) { if (kerberosPrincipalHostDAO.exists(evaluatedPrincipal, host)) { // There is nothing to do for this since it must already exist and we don't want to // regenerate the keytab message = String.format( "Skipping keytab file for %s, missing password indicates nothing to do", evaluatedPrincipal); LOG.debug(message); } else { KerberosPrincipalEntity principalEntity = kerberosPrincipalDAO .find(evaluatedPrincipal); String cachedKeytabPath = (principalEntity == null) ? null : principalEntity.getCachedKeytabPath(); if (cachedKeytabPath == null) { message = String.format( "Failed to create keytab for %s, missing cached file", evaluatedPrincipal); actionLog.writeStdErr(message); LOG.error(message); commandReport = createCommandReport(1, HostRoleStatus.FAILED, "{}", actionLog.getStdOut(), actionLog.getStdErr()); } else { try { operationHandler.createKeytabFile(new File(cachedKeytabPath), destinationKeytabFile); } catch (KerberosOperationException e) { message = String.format("Failed to create keytab file for %s - %s", evaluatedPrincipal, e.getMessage()); actionLog.writeStdErr(message); LOG.error(message, e); commandReport = createCommandReport(1, HostRoleStatus.FAILED, "{}", actionLog.getStdOut(), actionLog.getStdErr()); } } } } else { Keytab keytab = null; // Possibly get the keytab from the cache if (visitedPrincipalKeys != null) { // Since we have visited this principal before, attempt to pull the keytab from the // cache... KerberosPrincipalEntity principalEntity = kerberosPrincipalDAO .find(evaluatedPrincipal); String cachedKeytabPath = (principalEntity == null) ? null : principalEntity.getCachedKeytabPath(); if (cachedKeytabPath != null) { try { keytab = Keytab.read(new File(cachedKeytabPath)); } catch (IOException e) { message = String.format( "Failed to read the cached keytab for %s, recreating if possible - %s", evaluatedPrincipal, e.getMessage()); if (LOG.isDebugEnabled()) { LOG.warn(message, e); } else { LOG.warn(message, e); } } } } // If the keytab was not retrieved from the cache... create it. if (keytab == null) { Integer keyNumber = principalKeyNumberMap.get(evaluatedPrincipal); try { keytab = operationHandler.createKeytab(evaluatedPrincipal, password, keyNumber); // If the current identity does not represent a service, copy it to a secure location // and store that location so it can be reused rather than recreate it. KerberosPrincipalEntity principalEntity = kerberosPrincipalDAO .find(evaluatedPrincipal); if (principalEntity != null) { if (!principalEntity.isService() && ("true".equalsIgnoreCase( identityRecord.get(KEYTAB_FILE_IS_CACHABLE)))) { File cachedKeytabFile = cacheKeytab(evaluatedPrincipal, keytab); String previousCachedFilePath = principalEntity .getCachedKeytabPath(); String cachedKeytabFilePath = ((cachedKeytabFile == null) || !cachedKeytabFile.exists()) ? null : cachedKeytabFile.getAbsolutePath(); principalEntity.setCachedKeytabPath(cachedKeytabFilePath); kerberosPrincipalDAO.merge(principalEntity); if (previousCachedFilePath != null) { if (!new File(previousCachedFilePath).delete()) { LOG.debug(String.format( "Failed to remove orphaned cache file %s", previousCachedFilePath)); } } } } } catch (KerberosOperationException e) { message = String.format("Failed to create keytab file for %s - %s", evaluatedPrincipal, e.getMessage()); actionLog.writeStdErr(message); LOG.error(message, e); commandReport = createCommandReport(1, HostRoleStatus.FAILED, "{}", actionLog.getStdOut(), actionLog.getStdErr()); } } if (keytab != null) { try { if (operationHandler.createKeytabFile(keytab, destinationKeytabFile)) { ensureAmbariOnlyAccess(destinationKeytabFile); message = String.format("Successfully created keytab file for %s at %s", evaluatedPrincipal, destinationKeytabFile.getAbsolutePath()); LOG.debug(message); } else { message = String.format("Failed to create keytab file for %s at %s", evaluatedPrincipal, destinationKeytabFile.getAbsolutePath()); actionLog.writeStdErr(message); LOG.error(message); commandReport = createCommandReport(1, HostRoleStatus.FAILED, "{}", actionLog.getStdOut(), actionLog.getStdErr()); } } catch (KerberosOperationException e) { message = String.format("Failed to create keytab file for %s - %s", evaluatedPrincipal, e.getMessage()); actionLog.writeStdErr(message); LOG.error(message, e); commandReport = createCommandReport(1, HostRoleStatus.FAILED, "{}", actionLog.getStdOut(), actionLog.getStdErr()); } } } } else { message = String.format( "Failed to create keytab file for %s, the container directory does not exist: %s", evaluatedPrincipal, hostDirectory.getAbsolutePath()); actionLog.writeStdErr(message); LOG.error(message); commandReport = createCommandReport(1, HostRoleStatus.FAILED, "{}", actionLog.getStdOut(), actionLog.getStdErr()); } if (visitedPrincipalKeys == null) { visitedPrincipalKeys = new HashSet<String>(); visitedIdentities.put(evaluatedPrincipal, visitedPrincipalKeys); } visitedPrincipalKeys.add(visitationKey); } else { LOG.debug(String.format("Skipping previously processed keytab for %s on host %s", evaluatedPrincipal, host)); } } } } return commandReport; }
From source file:org.apache.ambari.server.serveraction.kerberos.CreateKeytabFilesServerAction.java
/** * Cache a keytab given its relative principal name and the keytab data. * <p/>/*from w w w .j a v a 2 s . c om*/ * The specified keytab is stored in a file in a location derived using the configured keytab * cache directory and the seeded hash of the principal name - this is to add a slight level * of obscurity so that it cannot be determined what keytab data is in the file based on its name. * The file is the set readable by only the Ambari server process owner. * * @param principal the principal name related to the keytab data * @param keytab the keytab data to cache * @return a File pointing to the cached keytab file * @throws AmbariException if a failure occurs while creating the cache file containing the the keytab data */ private File cacheKeytab(String principal, Keytab keytab) throws AmbariException { File cacheDirectory = configuration.getKerberosKeytabCacheDir(); if (cacheDirectory == null) { String message = "The Kerberos keytab cache directory is not configured in the Ambari properties"; LOG.error(message); throw new AmbariException(message); } if (!cacheDirectory.exists()) { // If the cache directory does not exist, create it and ensure only Ambari has access to it if (cacheDirectory.mkdirs()) { ensureAmbariOnlyAccess(cacheDirectory); if (!cacheDirectory.exists()) { String message = String.format("Failed to create the keytab cache directory %s", cacheDirectory.getAbsolutePath()); LOG.error(message); throw new AmbariException(message); } } } File cachedKeytabFile = new File(cacheDirectory, DigestUtils.sha1Hex(principal + String.valueOf(System.currentTimeMillis()))); try { keytab.write(cachedKeytabFile); ensureAmbariOnlyAccess(cachedKeytabFile); } catch (IOException e) { String message = String.format("Failed to write the keytab for %s to the cache location (%s)", principal, cachedKeytabFile.getAbsolutePath()); LOG.error(message, e); throw new AmbariException(message, e); } return cachedKeytabFile; }