Is it possible to completely mask a password with JLine? - masking

I'm using Spring Shell for a CLI and I want to read a password from the input line.
For such purpose spring shell has jline, so using the official documentation [1] of jline it suggests the following:
public static void main(String[] args) throws IOException {
String password = new ConsoleReader().readLine('*');
System.out.println("My password is: "+password);
}
When starting the application it looks like this:
mysecretpassword << entered by myself
**************** << masking from jline
My password is: mysecretpassword << my output
So my question is what is the purpose of masking the password if it is shown anyway, when I type it?
Is there a possibility to do it Unix style and don't even show the password, while typing it?
[1] http://jline.sourceforge.net/#installation

While you tagged your question with spring-shell, there is an open issue for support of masked (password) options.

For what it's worth, we implemented this feature directly (bypassing JLine) like so in Spring XD: (see UserInput.prompt())
https://github.com/spring-projects/spring-xd/blob/master/spring-xd-shell/src/main/java/org/springframework/xd/shell/command/ConsoleUserInput.java

Related

SendKeys() method ignores some characters when sending to a text box

I move my Selenium installation to a new server, since then some tests using logins no longer work.
After investigation, I found that the password field was populated with an incorrect value. Therefore the tests failed.
I'm trying to do the following :
_passWordTextBox.Clear();
_passWordTextBox.SendKeys("!!ä{dasd$352310!!!\\_XY>èà$£<?^^");
Here is how the field is populated after those lines:
The "!" character was the only one missing. It worked on the previous server. Some other suspicious characters (like $ éà<) also worked.
I've looked at locale settings (culture differences) between the servers.
From these characters sent in a Password string:
!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
All of these worked correctly:
"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\ _ abcdefghijklmnopqrstuvwxyz{|}
Only these failed to be sent correctly:
!]^`~
I've also tried in other fields (such as a Description field) and see the same failure.
I've tried to see if the command was sent correctly to the selenium server, but the logs seem to suggest it worked:
08:05:35.850 DEBUG [ReverseProxyHandler.execute] - To upstream: {"value":["!\"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~?"]}
It means that the server receives the command correctly, but for some reason the driver or the server doesn't execute properly.
Try this:
_passWordTextBox.SendKeys(#"!!ä{dasd$352310!!!\\_XY>èà$£<?^^");
Maybe is for the validates from field.
You can try using clipboard:
public static void SendValueFromClipboard(this IWebElement txtField, string value)
{
Clipboard.SetText(value);
txtField.SendKeys(OpenQA.Selenium.Keys.Control + "v");
}
This is written on C#, you will need to rewrite it in language, you are using.
After looking into multiple system settings i discovered that both my piloting and executing machine add the same regional settings (Format : French(Switzerland) , Keyboard : French(Switzerland), and I didn't look any further.
While fiddling around i discovered this setting :
As it turns out , the Language for non-Unicode programs was set to French(Switzerland) on the machine executing the tests. Changing it to English(UK) resolved the problem.
Probably a bug in chromedriver.
Your solution doesn't work for me, since I already have that setting set to English, but here's a solution I found if anyone else's interested.
Just change your keyboard to ENG UK in task bar.

Setting user credentials on aws instance using jclouds

I am trying to create an aws instance using jclouds 1.9.0 and then run a script on it (via ssh). I am following the example locate here but I am getting authentication failed errors when the client (java program) tries to connect at the instance. The AWS console show that instance is up and running.
The example tries to create a LoginCrendentials object
String user = System.getProperty("user.name");
String privateKey = Files.toString(new File(System.getProperty("user.home") + "/.ssh/id_rsa"), UTF_8);
return LoginCredentials.builder().user(user).privateKey(privateKey).build();
which is latter used from the ssh client
responses = compute.runScriptOnNodesMatching(
inGroup(groupName), // predicate used to select nodes
exec(command), // what you actually intend to run
overrideLoginCredentials(login) // use my local user & ssh key
.runAsRoot(false) // don't attempt to run as root (sudo)
.wrapInInitScript(false));
Some Login information are injected to the instance with following commands
Statement bootInstructions = AdminAccess.standard();
templateBuilder.options(runScript(bootInstructions));
Since I am on Windows machine the creation of LoginCrendentials 'fails' and thus I alter its code to
String user = "ec2-user";
String privateKey = "-----BEGIN RSA PRIVATE KEY-----.....-----END RSA PRIVATE KEY-----";
return LoginCredentials.builder().user(user).privateKey(privateKey).build();
I also to define the credentials while building the template as described in "EC2: In Depth" guide but with no luck.
An alternative is to build instance and inject the keypair as follows, but this implies that I need to have the ssh key stored in my AWS console, which is not currently the case and also breaks the functionality of running a script (via ssh) since I can not infer the NodeMetadata from a RunningInstance object.
RunInstancesOptions options = RunInstancesOptions.Builder.asType("t2.micro").withKeyName(keypair).withSecurityGroup(securityGroup).withUserData(script.getBytes());
Any suggestions??
Note: While I am currently testing this on aws, I want to keep the code as decoupled from the provider as possible.
Update 26/10/2015
Based on #Ignasi Barrera answer, I changed my implementation by adding .init(new MyAdminAccessConfiguration()) while creating the bootInstructions
Statement bootInstructions = AdminAccess.standard().init(new MyAdminAccessConfiguration());
templateBuilder.options(runScript(bootInstructions));
Where MyAdminAccessConfiguration is my own implementation of the AdminAccessConfiguration interface as #Ignasi Barrera described it.
I think the issue relies on the fact that the jclouds code runs on a Windows machine and jclouds makes some Unix assumptions by default.
There are two different things here: first, the AdminAccess.standard() is used to configure a user in the deployed node once it boots, and later the LoginCredentials object passed to the run script method is used to authenticate against the user that has been created with the previous statement.
The issue here is that the AdminAccess.standard() reads the "current user" information and assumes a Unix System. That user information is provided by this Default class, and in your case I'm pretty sure it will fallback to the catch block and return an auto-generated SSH key pair. That means, the AdminAccess.standard() is creating a user in the node with an auto-generated (random) SSH key, but the LoginCredentials you are building don't match those keys, thus the authentication failure.
Since the AdminAccess entity is immutable, the better and cleaner approach to fix this is to create your own implementation of the AdminAccessConfiguration interface. You can just copy the entire Default class and change the Unix specific bits to accommodate the SSH setup in your Windows machine. Once you have the implementation class, you can inject it by creating a Guice module and passing it to the list of modules provided when creating the jclouds context. Something like:
// Create the custom module to inject your implementation
Module windowsAdminAccess = new AbstractModule() {
#Override protected void configure() {
bind(AdminAccessConfiguration.class).to(YourCustomWindowsImpl.class).in(Scopes.SINGLETON);
}
};
// Provide the module in the module list when creating the context
ComputeServiceContext context = ContextBuilder.newBuilder("aws-ec2")
.credentials("api-key", "api-secret")
.modules(ImmutableSet.<Module> of(windowsAdminAccess, new SshjSshClientModule()))
.buildView(ComputeServiceContext.class);

Create a sqllte file with password [duplicate]

I'm just learning to use SQLite and I was curious if such is possible:
Encryption of the database file?
Password protect opening of the database?
PS. I know that there is this "SQLite Encryption Extension (SEE).", but according to the documentation, "The SEE is licensed software...." and "The cost of a perpetual source code license for SEE is US $2000."
SQLite has hooks built-in for encryption which are not used in the normal distribution, but here are a few implementations I know of:
SEE - The official implementation.
wxSQLite - A wxWidgets style C++ wrapper that also implements SQLite's encryption.
SQLCipher - Uses openSSL's libcrypto to implement.
SQLiteCrypt - Custom implementation, modified API.
botansqlite3 - botansqlite3 is an encryption codec for SQLite3 that can use any algorithms in Botan for encryption.
sqleet - another encryption implementation, using ChaCha20/Poly1305 primitives. Note that wxSQLite mentioned above can use this as a crypto provider.
The SEE and SQLiteCrypt require the purchase of a license.
Disclosure: I created botansqlite3.
You can password protect SQLite3 DB.
For the first time before doing any operations, set password as follows.
SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.open();
then next time you can access it like
conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();
This wont allow any GUI editor to view Your data.
Later if you wish to change the password, use conn.ChangePassword("new_password");
To reset or remove password, use conn.ChangePassword(String.Empty);
The .net library System.Data.SQLite also provides for encryption.
You can get sqlite3.dll file with encryption support from http://system.data.sqlite.org/.
1 - Go to http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki and download one of the packages. .NET version is irrelevant here.
2 - Extract SQLite.Interop.dll from package and rename it to sqlite3.dll. This DLL supports encryption via plaintext passwords or encryption keys.
The mentioned file is native and does NOT require .NET framework. It might need Visual C++ Runtime depending on the package you have downloaded.
UPDATE
This is the package that I've downloaded for 32-bit development: http://system.data.sqlite.org/blobs/1.0.94.0/sqlite-netFx40-static-binary-Win32-2010-1.0.94.0.zip
Keep in mind, the following is not intended to be a substitute for a proper security solution.
After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.
using System.Data.SQLite;
namespace EncryptDB
{
class Program
{
static void Main(string[] args)
{
string connectionString = #"C:\Programming\sqlite3\db.db";
string passwordString = "password";
byte[] passwordBytes = GetBytes(passwordString);
SQLiteConnection.CreateFile(connectionString);
SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
conn.SetPassword(passwordBytes);
conn.Open();
SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
sqlCmd.ExecuteNonQuery();
sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
sqlCmd.ExecuteNonQuery();
conn.Close();
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
bytes = System.Text.Encoding.Default.GetBytes(str);
return bytes;
}
}
}
Optionally, you can remove conn.SetPassword(passwordBytes);, and replace it with conn.ChangePassword("password"); which needs to be placed after conn.Open(); instead of before. Then you won't need the GetBytes method.
To decrypt, it's just a matter of putting the password in your connection string before the call to open.
string filename = #"C:\Programming\sqlite3\db.db";
string passwordString = "password";
SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
conn.Open();
You can always encrypt data on the client side. Please note that not all of the data have to be encrypted because it has a performance issue.
You can use SQLite's function creation routines (PHP manual):
$db_obj->sqliteCreateFunction('Encrypt', 'MyEncryptFunction', 2);
$db_obj->sqliteCreateFunction('Decrypt', 'MyDecryptFunction', 2);
When inserting data, you can use the encryption function directly and INSERT the encrypted data or you can use the custom function and pass unencrypted data:
$insert_obj = $db_obj->prepare('INSERT INTO table (Clear, Encrypted) ' .
'VALUES (:clear, Encrypt(:data, "' . $passwordhash_str . '"))');
When retrieving data, you can also use SQL search functionality:
$select_obj = $db_obj->prepare('SELECT Clear, ' .
'Decrypt(Encrypted, "' . $passwordhash_str . '") AS PlainText FROM table ' .
'WHERE PlainText LIKE :searchterm');
Well, SEE is expensive. However SQLite has interface built-in for encryption (Pager). This means, that on top of existing code one can easily develop some encryption mechanism, does not have to be AES. Anything really.
Please see my post here: https://stackoverflow.com/a/49161716/9418360
You need to define SQLITE_HAS_CODEC=1 to enable Pager encryption. Sample code below (original SQLite source):
#ifdef SQLITE_HAS_CODEC
/*
** This function is called by the wal module when writing page content
** into the log file.
**
** This function returns a pointer to a buffer containing the encrypted
** page content. If a malloc fails, this function may return NULL.
*/
SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
void *aData = 0;
CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
return aData;
}
#endif
There is a commercial version in C language for SQLite encryption using AES256 - it can also work with PHP, but it needs to be compiled with PHP and SQLite extension. It de/encrypts SQLite database file on the fly, file contents are always encrypted. Very useful.
http://www.iqx7.com/products/sqlite-encryption
I had also similar problem. Needed to store sensitive data in simple database (SQLite was the perfect choice except security). Finally I have placed database file on TrueCrypt encrypted valume.
Additional console app mounts temporary drive using TrueCrypt CLI and then starts the database application. Waits until the database application exits and then dismounts the drive again.
Maybe not suitable solution in all scenarios but for me working well ...

How can I interact with the user inside a CasperJS/PhantomJS script?

Imagine a script like
system = require "system"
system.stdout.write "What's your name? "
name = system.stdin.readLine()
system.stdout.writeLine "Hello, #{name}"
To be run via
casperjs name.coffee
I'd like to be able to interact with the user in the terminal used to run the script, but I get stuck in the readLine() call.
As GarethOwen pointed out, it is indeed possible.
Here is a very basic CasperJS implementation of the Unix command cat:
var system = require('system'),
casper = require('casper').create();
while (!system.stdin.atEnd()) {
var line = system.stdin.readLine();
casper.log(line);
}
casper.exit();
Note that this module is mostly implemented in C++:
https://github.com/ariya/phantomjs/blob/master/src/system.h
And that stdin / stdout / stderr are instances of the PhantomJs class File :
https://github.com/ariya/phantomjs/blob/master/src/filesystem.h
According to the documentation, phantomJS can communicate with standard input. See this example:
https://github.com/ariya/phantomjs/blob/master/examples/stdin-stdout-stderr.js
Documentation regarding inter-process communication is here:
https://github.com/ariya/phantomjs/wiki/Inter-Process-Communication
But I've never tried it myself.

Issue with setting ADMIN password on Windows CE

I have wrote a user manager script the uses NTLMSetUserInfo to set passwords of some users, including ADMIN... What I have noticed though is that if I do this the username / password combination works perfectly for all scenarios such as Telnet, HTTP Auth etc but NOT file browsing.
Upon further inspection I noticed that when setting the Admin password through the built in CE configuration web pages it works.
The registry for Admin looks like so when I use NTLMSetUserInfo
NT = [hex value]
The registry for Admin contains an extra field, Password when I set the admin password via the CE web pages.
NT = [hex value]
Password = [hex value]
I figure NTLMSetUserInfo doesn't set the global CE password for Admin properly, hence not being able to file browse onto the box.
I found the following function in the CE web code parsing DLL that does the job called SetPassword. I wrote a separate function to deal with Admin cases but I cannot get it to compile. Here is a snippet of it
#include <windbase.h>
bool UserAccounts::SetAdminPassword(const std::string &passwordOld, const std::string &password)
{
wchar_t wpass[512];
wchar_t wpassold[512];
mbstowcs(wpass, password.c_str(), 512);
mbstowcs(wpassold, passwordOld.c_str(), 512);
return SetPassword(wpassold, wpass) == TRUE;
}
This will not compile stating that 'SetPassword': identifier not found. I notice in the CE documentation for SetPassword it has the following line
To use this function, you must include
the password component, Fspass, in
your Cesysgen.bat file.
I'm not sure what this means as I am pretty new to PlatformBuilder etc...
Can anyone help me or point me in the right direction?
Add the following to the top of your code file:
extern "C" BOOL SetPassword(LPWSTR lpszOldPassword, LPWSTR lpszNewPassword);
The linker will do the rest.
I can't give an exact answer right now (never used this authentication). But, I just tried to use (actually compile) SetPassword in a cloned version of the bluetooth AudioGateway driver I have and it compiles without problems.
When I tried to use it in a subproject or a regular independent project I had the same error that you got. So a quick solution might be to do this in a driver and see if it works.
Regarding the comment in the docs I assume they it goes down to having the SYSGEN_FSPASSWORD selected in the catalog though I did not trace this yet. I guess you have this selected if you can set passwords and such.