use of java.security.KeyException in project scheduling by ow2-proactive.
the class SchedulerProxyUserInterface method init.
/**
* initialize the connection the scheduler.
* Must be called only once.
* Create the corresponding credential object before sending it
* to the scheduler.
* @param url the scheduler's url
* @param credData the credential object that contains user-related data
* @throws SchedulerException thrown if the scheduler is not available
* @throws LoginException if the couple username/password is invalid
* @since Scheduling 3.1.0
*/
public void init(String url, CredData credData) throws SchedulerException, LoginException {
SchedulerAuthenticationInterface auth = SchedulerConnection.join(url);
PublicKey pubKey = auth.getPublicKey();
try {
Credentials cred = Credentials.createCredentials(credData, pubKey);
this.uischeduler = auth.login(cred);
mbeaninfoviewer = new MBeanInfoViewer(auth, credData.getLogin(), cred);
} catch (KeyException e) {
throw new InternalSchedulerException(e);
}
}
use of java.security.KeyException in project scheduling by ow2-proactive.
the class ManageUsers method manageUsers.
public static void manageUsers(String... args) throws ManageUsersException {
SecurityManagerConfigurator.configureSecurityManager(CreateCredentials.class.getResource("/all-permissions.security.policy").toString());
Console console = System.console();
/**
* default values
*/
String pubKeyPath = null;
PublicKey pubKey = null;
UserInfo userInfo = new UserInfo();
String loginFilePath = getLoginFilePath();
String groupFilePath = getGroupFilePath();
String sourceLoginFilePath = null;
String sourceGroupFilePath = null;
Action action = null;
Options options = new Options();
CommandLine cmd = getCommandLine(args, loginFilePath, groupFilePath, options);
if (cmd.hasOption(HELP_OPTION_NAME) || cmd.getOptions().length == 0) {
displayHelp(options);
return;
}
action = Action.getAction(cmd);
if (cmd.hasOption(LOGIN_OPTION_NAME)) {
userInfo.setLogin(cmd.getOptionValue(LOGIN_OPTION_NAME));
}
if (cmd.hasOption(PWD_OPTION_NAME)) {
userInfo.setPassword(cmd.getOptionValue(PWD_OPTION_NAME));
}
if (cmd.hasOption(GROUPS_OPTION_NAME)) {
String groupString = cmd.getOptionValue(GROUPS_OPTION_NAME);
userInfo.setGroups(Arrays.asList(groupString.split(",")));
}
if (cmd.hasOption(LOGINFILE_OPTION_NAME)) {
loginFilePath = cmd.getOptionValue(LOGINFILE_OPTION_NAME);
}
if (cmd.hasOption(GROUPFILE_OPTION_NAME)) {
groupFilePath = cmd.getOptionValue(GROUPFILE_OPTION_NAME);
}
if (cmd.hasOption(KEYFILE_OPTION_NAME)) {
pubKeyPath = cmd.getOptionValue(KEYFILE_OPTION_NAME);
}
if (cmd.hasOption(SOURCE_LOGINFILE_OPTION_NAME)) {
if (action == Action.DELETE) {
exitWithErrorMessage("Cannot use action delete with source login file.", null, null);
}
if (!cmd.hasOption(SOURCE_GROUPFILE_OPTION_NAME) && action == Action.CREATE) {
exitWithErrorMessage("Source group file must be provided when creating users with source login file.", null, null);
}
sourceLoginFilePath = cmd.getOptionValue(SOURCE_LOGINFILE_OPTION_NAME);
userInfo = null;
}
if (cmd.hasOption(SOURCE_GROUPFILE_OPTION_NAME)) {
if (action == Action.DELETE) {
exitWithErrorMessage("Cannot use action delete with source group file.", null, null);
}
if (!cmd.hasOption(SOURCE_LOGINFILE_OPTION_NAME) && action == Action.CREATE) {
exitWithErrorMessage("Source login file must be provided when creating users with source group file.", null, null);
}
sourceGroupFilePath = cmd.getOptionValue(SOURCE_GROUPFILE_OPTION_NAME);
userInfo = null;
}
if (pubKeyPath == null) {
pubKeyPath = getPublicKeyFilePath();
}
try {
pubKey = Credentials.getPublicKey(pubKeyPath);
} catch (KeyException e) {
exitWithErrorMessage("Could not retrieve public key from '" + pubKeyPath, null, e);
}
boolean nonInteractive = checkInteractivity(userInfo, sourceLoginFilePath, sourceGroupFilePath, action);
if (!nonInteractive) {
askInteractively(console, userInfo, action);
}
updateAccounts(pubKey, userInfo, loginFilePath, groupFilePath, action, sourceLoginFilePath, sourceGroupFilePath);
}
use of java.security.KeyException in project scheduling by ow2-proactive.
the class AuthenticationImpl method authenticate.
/**
* Performs login.
*
* @param cred encrypted username and password
* @return the name of the user logged
* @throws LoginException if username or password is incorrect.
*/
public Subject authenticate(Credentials cred) throws LoginException {
if (activated == false) {
throw new LoginException("Authentication active object is not activated.");
}
CredData credentials = null;
try {
credentials = cred.decrypt(privateKeyPath);
} catch (KeyException e) {
throw new LoginException("Could not decrypt credentials: " + e);
}
String username = credentials.getLogin();
String password = credentials.getPassword();
if (username == null || username.equals("")) {
throw new LoginException("Bad user name (user is null or empty)");
}
try {
// Verify that this user//password can connect to this existing scheduler
getLogger().info(username + " is trying to connect");
Map<String, Object> params = new HashMap<>(4);
// user name to check
params.put("username", username);
// password to check
params.put("pw", password);
// Load LoginContext according to login method defined in jaas.config
LoginContext lc = new LoginContext(getLoginMethod(), new NoCallbackHandler(params));
lc.login();
getLogger().info("User " + username + " logged successfully");
return lc.getSubject();
} catch (LoginException e) {
getLogger().info(e.getMessage());
// user about the reason of non authentication
throw new LoginException("Authentication failed");
}
}
use of java.security.KeyException in project scheduling by ow2-proactive.
the class CreateCredentials method main.
/**
* Entry point
*
* @see org.ow2.proactive.authentication.crypto.Credentials
* @param args arguments, try '-h' for help
* @throws IOException
* @throws ParseException
*/
public static void main(String[] args) throws IOException, ParseException {
SecurityManagerConfigurator.configureSecurityManager(CreateCredentials.class.getResource("/all-permissions.security.policy").toString());
Console console = System.console();
/**
* default values
*/
boolean interactive = true;
String pubKeyPath = null;
PublicKey pubKey = null;
String login = null;
String pass = null;
String keyfile = null;
String cipher = "RSA/ECB/PKCS1Padding";
String path = Credentials.getCredentialsPath();
String rm = null;
String scheduler = null;
String url = null;
Options options = new Options();
Option opt = new Option("h", "help", false, "Display this help");
opt.setRequired(false);
options.addOption(opt);
OptionGroup group = new OptionGroup();
group.setRequired(false);
opt = new Option("F", "file", true, "Public key path on the local filesystem [default:" + Credentials.getPubKeyPath() + "]");
opt.setArgName("PATH");
opt.setArgs(1);
opt.setRequired(false);
group.addOption(opt);
opt = new Option("R", "rm", true, "Request the public key to the Resource Manager at URL");
opt.setArgName("URL");
opt.setArgs(1);
opt.setRequired(false);
group.addOption(opt);
opt = new Option("S", "scheduler", true, "Request the public key to the Scheduler at URL");
opt.setArgName("URL");
opt.setArgs(1);
opt.setRequired(false);
group.addOption(opt);
options.addOptionGroup(group);
opt = new Option("l", "login", true, "Generate credentials for this specific user, will be asked interactively if not specified");
opt.setArgName("LOGIN");
opt.setArgs(1);
opt.setRequired(false);
options.addOption(opt);
opt = new Option("p", "password", true, "Use this password, will be asked interactively if not specified");
opt.setArgName("PWD");
opt.setArgs(1);
opt.setRequired(false);
options.addOption(opt);
opt = new Option("k", "keyfile", true, "Use specified ssh private key, asked interactively if specified without PATH, not specified otherwise.");
opt.setArgName("PATH");
opt.setOptionalArg(true);
opt.setRequired(false);
options.addOption(opt);
opt = new Option("o", "output", true, "Output the resulting credentials to the specified file [default:" + path + "]");
opt.setArgName("PATH");
opt.setArgs(1);
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "cipher", true, "Use specified cipher parameters, need to be compatible with the specified key [default:" + cipher + "]");
opt.setArgName("PARAMS");
opt.setArgs(1);
opt.setRequired(false);
options.addOption(opt);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (Exception e) {
System.err.println(newline + "ERROR : " + e.getMessage() + newline);
System.out.println("type -h or --help to display help screen");
System.exit(1);
}
if (cmd.hasOption("help")) {
displayHelp(options);
}
if (cmd.hasOption("file")) {
pubKeyPath = cmd.getOptionValue("file");
}
if (cmd.hasOption("rm")) {
rm = cmd.getOptionValue("rm");
}
if (cmd.hasOption("scheduler")) {
scheduler = cmd.getOptionValue("scheduler");
}
if (cmd.hasOption("login")) {
login = cmd.getOptionValue("login");
}
if (cmd.hasOption("password")) {
pass = cmd.getOptionValue("password");
}
if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
keyfile = cmd.getOptionValue("keyfile");
}
if (cmd.hasOption("output")) {
path = cmd.getOptionValue("output");
}
if (cmd.hasOption("cipher")) {
cipher = cmd.getOptionValue("cipher");
}
int acc = 0;
if (pubKeyPath != null) {
acc++;
}
if (scheduler != null) {
url = URIBuilder.buildURI(Connection.normalize(scheduler), "SCHEDULER").toString();
acc++;
}
if (rm != null) {
url = URIBuilder.buildURI(Connection.normalize(rm), "RMAUTHENTICATION").toString();
acc++;
}
if (acc > 1) {
System.out.println("--rm, --scheduler and --file arguments cannot be combined.");
System.out.println("try -h for help.");
System.exit(1);
}
if (url != null) {
try {
Connection<AuthenticationImpl> conn = new Connection<AuthenticationImpl>(AuthenticationImpl.class) {
public Logger getLogger() {
return Logger.getLogger("pa.scheduler.credentials");
}
};
AuthenticationImpl auth = conn.connect(url);
pubKey = auth.getPublicKey();
} catch (Exception e) {
System.err.println("ERROR : Could not retrieve public key from '" + url + "'");
e.printStackTrace();
System.exit(3);
}
System.out.println("Successfully obtained public key from " + url + newline);
} else if (pubKeyPath != null) {
try {
pubKey = Credentials.getPublicKey(pubKeyPath);
} catch (KeyException e) {
System.err.println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
System.exit(4);
}
} else {
System.out.println("No public key specified, attempting to retrieve it from default location.");
pubKeyPath = Credentials.getPubKeyPath();
try {
pubKey = Credentials.getPublicKey(pubKeyPath);
} catch (KeyException e) {
System.err.println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
System.exit(5);
}
}
if (login != null && pass != null && (!cmd.hasOption("keyfile") || cmd.getOptionValues("keyfile") != null)) {
System.out.println("Running in non-interactive mode." + newline);
interactive = false;
} else {
System.out.println("Running in interactive mode.");
}
if (interactive) {
System.out.println("Please enter Scheduler credentials,");
System.out.println("they will be stored encrypted on disk for future logins." + newline);
System.out.print("login: ");
if (login == null) {
login = console.readLine();
} else {
System.out.println(login);
}
System.out.print("password: ");
if (pass == null) {
pass = new String(console.readPassword());
} else {
System.out.println("*******");
}
System.out.print("keyfile: ");
if (!cmd.hasOption("keyfile")) {
System.out.println("no key file specified");
} else if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
System.out.println(keyfile);
} else {
keyfile = console.readLine();
}
}
try {
CredData credData;
if (keyfile != null && keyfile.length() > 0) {
byte[] keyfileContent = FileToBytesConverter.convertFileToByteArray(new File(keyfile));
credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass, keyfileContent);
} else {
System.out.println("--> Ignoring keyfile, credential does not contain SSH key");
credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass);
}
Credentials cred = Credentials.createCredentials(credData, pubKey, cipher);
cred.writeToDisk(path);
} catch (FileNotFoundException e) {
System.err.println("ERROR : Could not retrieve ssh private key from '" + keyfile + "' (no such file)");
System.exit(6);
} catch (Throwable t) {
t.printStackTrace();
System.exit(7);
}
System.out.println("Successfully stored encrypted credentials on disk at :");
System.out.println("\t" + path);
System.exit(0);
}
use of java.security.KeyException in project scheduling by ow2-proactive.
the class Credentials method getPublicKey.
/**
* Retrieves a public key stored in a local file
* <p>
*
* @param pubPath path to the public key on the local filesystem
* @return the key encapsulated in a regular JCE container
* @throws KeyException the key could not be retrieved or is malformed
*/
public static PublicKey getPublicKey(String pubPath) throws KeyException {
String algo = "", tmp = "";
byte[] bytes;
File f = new File(pubPath);
// recover public key bytes
try (DataInputStream in = new DataInputStream(new FileInputStream(f))) {
int read, tot = 0;
while ((read = in.read()) != '\n') {
algo += (char) read;
tot++;
}
tot++;
while ((read = in.read()) != '\n') {
tmp += (char) read;
tot++;
}
tot++;
bytes = new byte[(int) f.length() - tot];
in.readFully(bytes);
} catch (Exception e) {
throw new KeyException("Could not retrieve public key from " + pubPath, e);
}
// reconstruct public key
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes);
PublicKey pubKey;
KeyFactory keyFactory;
try {
keyFactory = KeyFactory.getInstance(algo);
} catch (NoSuchAlgorithmException e) {
throw new KeyException("Cannot initialize key factory", e);
}
try {
pubKey = keyFactory.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException e) {
throw new KeyException("Cannot re-generate public key", e);
}
return pubKey;
}
Aggregations