Hide password in Genexus beforeConnect procedure - genexus

I'm using the BeforeConnect option in Genexus. I put this code in a procedure...
&UserID = &websession.Get("db")
//select the Database depending on websession
Do Case
Case &UserID = "1"
&DataBase = "CambioDB1"
Case &UserID = "2"
&DataBase = "CambioDB2"
Otherwise
&DataBase = "CambioDB1" //default database
EndCase
//Change connection properties
&dbconn = GetDatastore("Default")
&dbconn.UserName = 'username'
&dbconn.UserPassword = 'password'
&dbconn.ConnectionData = "DATABASE=" + &DataBase.Trim() //SQLServer
... set the BeforeConnect property and it works.
But how can I avoid to put the password of the db in the code?
I was thinking to use a file to read from, but it would be an unencrypted password anyway.
How can I solve this? Is there a way to manage this or do I have to risk the password in clear text?

Nicola,
You may use the ConfigurationManager to read a value from the standard config file (client.cfg for Java, web.config for .net).
&MyPassword = ConfigurationManager.GetValue('MY_PASSWORD')
Add a value to your configuration file with the password.
For example:
MY_PASSWORD=my-db-password
You probably want to save the password encrypted for an extra layer of security.
Simple:
&EncPass = Encrypt64(&Password, &SysEncKey)
Stonger encryption:
https://wiki.genexus.com/commwiki/servlet/wiki?42682,Symmetric+Stream+Encryption
&EncPass = &SymmetricStreamCipher.DoEncrypt(symmetricStreamAlgorithm, key, iv, plainText)

Related

How to configure RoundCubeMail so I can log in

I am trying to set up roundcubemail on a mac so that I can eventually add an email-pipe to service certain emails. I have followed the installation and configuration options the best I can, and the tests show no problems except with the test send an email and the iMap test. The instructions are not very clear about how to set up parts of the config.inc.php. Here is my config.inc.php:
<?php
/* Local configuration for Roundcube Webmail */
// ----------------------------------
// SQL DATABASE
// ----------------------------------
// Database connection string (DSN) for read+write operations
// Format (compatible with PEAR MDB2): db_provider://user:password#host/database
// Currently supported db_providers: mysql, pgsql, sqlite, mssql, sqlsrv, oracle
// For examples see http://pear.php.net/manual/en/package.database.mdb2.intro-dsn.php
// Note: for SQLite use absolute path (Linux): 'sqlite:////full/path/to/sqlite.db?mode=0646'
// or (Windows): 'sqlite:///C:/full/path/to/sqlite.db'
// Note: Various drivers support various additional arguments for connection,
// for Mysql: key, cipher, cert, capath, ca, verify_server_cert,
// for Postgres: application_name, sslmode, sslcert, sslkey, sslrootcert, sslcrl, sslcompression, service.
// e.g. 'mysql://roundcube:#localhost/roundcubemail?verify_server_cert=false'
$config['db_dsnw'] = 'mysql://roundcubemail:roundcubemail_db_password#localhost/roundcubemail';
// Syslog ident string to use, if using the 'syslog' log driver.
$config['syslog_id'] = 'webmail';
// ----------------------------------
// IMAP
// ----------------------------------
// The IMAP host chosen to perform the log-in.
// Leave blank to show a textbox at login, give a list of hosts
// to display a pulldown menu or set one host as string.
// Enter hostname with prefix ssl:// to use Implicit TLS, or use
// prefix tls:// to use STARTTLS.
// Supported replacement variables:
// %n - hostname ($_SERVER['SERVER_NAME'])
// %t - hostname without the first part
// %d - domain (http hostname $_SERVER['HTTP_HOST'] without the first part)
// %s - domain name after the '#' from e-mail address provided at login screen
// For example %n = mail.domain.tld, %t = domain.tld
// WARNING: After hostname change update of mail_host column in users table is
// required to match old user data records with the new host.
$config['default_host'] = 'localhost';
//$config['default_host'] = 'ssh://%n';
$config['imap_conn_options'] = array(
'ssl' => array(
'verify_peer' => false,
'verfify_peer_name' => false,
),
);
$config['smtp_conn_options'] = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
);
// provide an URL where a user can get support for this Roundcube installation
// PLEASE DO NOT LINK TO THE ROUNDCUBE.NET WEBSITE HERE!
$config['support_url'] = 'mailto://support_email';
// This key is used for encrypting purposes, like storing of imap password
// in the session. For historical reasons it's called DES_key, but it's used
// with any configured cipher_method (see below).
$config['des_key'] = 'aKey';
// Name your service. This is displayed on the login screen and in the window title
$config['product_name'] = 'Webmail';
// ----------------------------------
// PLUGINS
// ----------------------------------
// List of active plugins (in plugins/ directory)
$config['plugins'] = array('archive', 'attachment_reminder', 'emoticons', 'markasjunk', 'new_user_dialog', 'userinfo', 'vcard_attachments');
// the default locale setting (leave empty for auto-detection)
// RFC1766 formatted language name like en_US, de_DE, de_CH, fr_FR, pt_BR
$config['language'] = 'en_US';
The iMap and ssl portions are what is confusing to me. I would like to use the email server on localhost to send emails. The problem is that after I get it installed, when I access http://localhost/webmail, a login form shows up. I don't know what to enter for userid or password as I've never specified them when doing the configuration. I selected auto add new users, but nothing happens.
This is the log entry:
[18-May-2020 19:29:54 -0400]: <d2s7trm8>
IMAP Error: Login failed for userid against localhost from 127.0.0.1(X-Forwarded-For: ::1).
Authentication failed. in /Library/Server/Web/Data/Sites/Default/webmail/program/lib/Roundcube/rcube_imap.php
on line 200 (POST /webmail/?_task=login&_action=login)
What steps do I take to get the iMap and ssl ( if I need it ) to work?
I believe I found my error. Ignorance on my part. I was able to log into my round cube webmail on my own server by logging in using my account username and password. I had set the IMAP server to be local host but kept thinking I was supposed to use my local (Apple) email address or such.
When reading installations, it is important to understand that the writer knows things you don’t and doesn’t always explain in detail things that are obvious to them. Reading on the side things about how IMAP servers actually work helped out here to clarify what some of the terms were talking about.
Nice interface once you get logged in!

How do I make uCanAccess use Samba authentication, with special characters in username or password?

TL;DR: What Database.FileFormat constant should I use for an MS Access 2000-2003 database, when creating the Database object?
I have built a SAMBA test application using jCIFS. It allows me to create/overwrite files if given the correct authentication credentials, regardless of on which PC in the domain I use it.
I also have an application that uses uCanAccess/jackcess to connect to an MDB on a network share. However (from what I understand), it uses the credentials of the logged-in user, a number of whom have read-only access. Only system/network administrators have write permission.
The database in question is not password-protected. (I don't need to enter a password when opening it.)
My intention is to have the app ask for the administrator's Samba credentials before it writes to the DB, using those in the uCanAccess connection, so that it doesn't throw a java.nio.channels.NonWritableChannelException, as per the below stack trace:
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:747)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:310)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:247)
at com.healthmarketscience.jackcess.impl.TableImpl.writeDataPage(TableImpl.java:1980)
at com.healthmarketscience.jackcess.impl.TableImpl.addRows(TableImpl.java:2229)
at com.healthmarketscience.jackcess.impl.TableImpl.addRow(TableImpl.java:2067)
at net.ucanaccess.converters.UcanaccessTable.addRow(UcanaccessTable.java:44)
at net.ucanaccess.commands.InsertCommand.insertRow(InsertCommand.java:101)
at net.ucanaccess.commands.InsertCommand.persist(InsertCommand.java:148)
at net.ucanaccess.jdbc.UcanaccessConnection.flushIO(UcanaccessConnection.java:315)
at net.ucanaccess.jdbc.UcanaccessConnection.commit(UcanaccessConnection.java:205)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:217)
at net.ucanaccess.jdbc.Execute.execute(Execute.java:46)
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.execute(UcanaccessPreparedStatement.java:228)
at myapp.db.Digger.addTransaction(Digger.java:993)
at myapp.tasks.TransactionRunnable.run(TransactionRunnable.java:42)
at java.lang.Thread.run(Thread.java:745)
Update: I have tried using the smbFileChannel class by Gord Thompson and J. T. Alhborn, shown here. My code, based off the main class shown in that answer, looks like this:
// Ask the user for login credentials and the path to the database
String smbURL = (chosenDir.endsWith("/") ? chosenDir : chosenDir + '/')
+ dbName;
System.out.println("DB Path to use for URL: " + smbURL);
URL u = new URL(smbURL);
try (
// construct the SMB DB URL
SmbFileChannel sfc = new SmbFileChannel(smbURL);
Database db = new DatabaseBuilder().setChannel(sfc)
.setFileFormat(Database.FileFormat.GENERIC_JET4).create();
) {
// Model the table
Table tbl = new TableBuilder("Transactions")
.addColumn(new ColumnBuilder("TransactionID", DataType.LONG).setAutoNumber(true))
.addColumn(new ColumnBuilder("ControllerID", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("ReaderID", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("Event", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("Timestamp", DataType.SHORT_DATE_TIME).setAutoNumber(false))
.addColumn(new ColumnBuilder("Number", DataType.LONG).setAutoNumber(false))
.addIndex(new IndexBuilder(IndexBuilder.PRIMARY_KEY_NAME).addColumns("TransactionID").setPrimaryKey())
.toTable(db);
// Add the row
Map<String, Object> values = new HashMap<>();
values.put("ControllerID", cid);
values.put("ReaderID", rid);
values.put("Event", evtNum);
values.put("Timestamp", ts); // Long; must be converted to DataType.SHORT_DATE_TIME
values.put("Number", accNum);
tbl.addRowFromMap(values);
} catch (IOException IOEx) {
System.err.println(
"Failed to write record to Transactions table in database: "
+ IOEx.getMessage()
);
IOEx.printStackTrace(System.err);
} catch (Exception ex) {
System.err.println(
'[' + ex.getClass().getSimpleName() + "]: Failed to write record to "
+ "Transactions table in database: " + ex.getMessage()
);
ex.printStackTrace(System.err);
}
Executing the above code results in the following output:
DB Path to use for URL: smb://machine.vpnName/Storage/me/dbs/DBName.mdb
Failed to write record to Transactions table in database: Logon failure: account currently disabled.
jcifs.smb.SmbAuthException: Logon failure: account currently disabled.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:546)
at jcifs.smb.SmbTransport.send(SmbTransport.java:663)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:390)
at jcifs.smb.SmbSession.send(SmbSession.java:218)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:176)
at jcifs.smb.SmbFile.doConnect(SmbFile.java:911)
at jcifs.smb.SmbFile.connect(SmbFile.java:957)
at jcifs.smb.SmbFile.connect0(SmbFile.java:880)
at jcifs.smb.SmbFile.open0(SmbFile.java:975)
at jcifs.smb.SmbFile.open(SmbFile.java:1009)
at jcifs.smb.SmbRandomAccessFile.<init>(SmbRandomAccessFile.java:57)
at jcifs.smb.SmbRandomAccessFile.<init>(SmbRandomAccessFile.java:42)
at samba.SmbFileChannel.<init>(SmbFileChannel.java:30)
at samba.SambaLanWriteTest.writeTest(SambaLanWriteTest.java:130)
at samba.SambaLanWriteTest.main(SambaLanWriteTest.java:181)
I have write access to a test copy of the database file in question when using Windows File Explorer. I am choosing that one when prompted.
Update 2: I realised that I neglected to add my username and password to the smb:// URL, as Thompson's example shows. I changed to code to this:
String smbCred = "smb://" + auth.getUsername() + ":" + auth.getPassword() + "#",
fixer = chosenDir.replace("\\", "/").replace("smb://", smbCred),
smbURL = fixer + dbName;
System.out.println("DB Path to use for URL: " + smbURL);
// URL u = new URL(smbURL);
The next problem I had was that my password contains special illegal characters (such as '#', ':', ';', '=' and '?'). I escaped these by using java.net.URLEncoder.encode() on auth.getUsername() and auth.getPassword() so the code doesn't throw a MalformedURLException when creating the SmbChannel. However, the next exception I encountered is as follows:
Failed to write record to Transactions table in database: File format GENERIC_JET4 [VERSION_4] does not support file creation for null
java.io.IOException: File format GENERIC_JET4 [VERSION_4] does not support file creation for null
at com.healthmarketscience.jackcess.impl.DatabaseImpl.create(DatabaseImpl.java:444)
What Database.FileFormat constant should I use for an MS Access 2000-2003 database, when creating the Database object?
It turns out that I needed to use Database.FileFormat.V2000.
After that, it was all plain sailing (although I still need to work out how to get the Long timestamp to convert correctly).

How to save a file with password in UFT

I am using UFT 12.5. During run time it opens excel and word. Then it writes some data in the both files. After that, I would like to save both files with a new name and then password protected. I need to be able to enter password manually to open it. So far, I have written the below code and I getting an error at the last line.
Set ExcelObj = createobject("excel.application")
ExcelObj.Visible = true
Set ExcelFile = ExcelObj.Workbooks.Open (file)
Set ScripSheet = ExcelFile.Worksheets("Scripts")
ScripSheet.Cells(1,1) = "Passed"
ExcelFile.SaveAs mm1, "ttt"
Please advise on how I can save word and excel files with a password using UFT.
Thanks.
You need to pass correct parameters with SaveAs method. Check this link for more info.
Here is the working code that you can try:
file = "File path with file name"
newfile = "File path with new file name"
Set ExcelObj = createobject("excel.application")
ExcelObj.Visible = true
Set ExcelFile = ExcelObj.Workbooks.Open (file)
Set ScripSheet = ExcelFile.Worksheets("Scripts")
ScripSheet.Cells(1,1) = "Passed"
ExcelFile.SaveAs newfile, , "test"
ExcelFile.Close
ExcelObj.Quit
UPDATE
Per comments from OP
If you want to save file with ReadOnly, you have to use WriteResPassword parameter this way:
ExcelFile.SaveAs newfile, , , "test"
Note that I've two empty parameters for FileFormat and
Password respectively.
This way it will ask for password to open the file in write mode and if you won't provide the password, file will be opened in ReadOnly
mode.
Check the link that I've mentioned.

How to get properties of Authentification Alias on WAS 7 using wsadmin

I created a script in Jython which extracts some properties of a Data Source from WAS 7. One of theese properties is the Authentification Alias. I know that the password is crypted, but project has a semididactical purpose so the focus is on retriving the username and password, not to hack something.
How can I extract the properties of the Authentification Alias, i mean the username and the password?
Thanks in advance!
I solved the problem. :) Let's start with the beginning.
You have to find security.xml (WAS_HOME/AppServer/profiles/Profile_Name/config/cells/Cell_Name/security.xml) file and search in it the Authentication Alias.
Keep the line that contains the Auth Alias in a variable called Line and then extract the username, password and description.
After that you have to decrypt your password with a XOR algorithm, and write the variables in a file as a list. Ex: AuthDataAlias = [\ ['AuthAlias', 'username', 'password', 'description'] ]
Code:
import sys, java, java.io, java.lang, base64, binascii
resFile="resources.res"
def search ( alias, file ):
f=open(file)
lines=f.readlines()
for line in lines:
poz = line.find('/'+alias)
if poz > 0:
Line = line
break
user = Line[Line.find('userId=')+8:Line.find('\" password')]
password = Line[Line.find('password=')+15:Line.find('\" description')]
password = decrypt(password)
description = Line[Line.find('description=')+13:Line.find('\"/>')]
write ( AuthAlias, user, password, description, resFile)
def write ( alias, user, password, desc, file ):
objItemFileOutputStream = java.io.FileOutputStream(file, 1) #apend la sfirsit fisier
objItemFileOutputStream.write('\n')
AuthList = "AuthDataAlias = [\\\n[\'"+alias+"\', \'"+user+"\', \'"+password+"\', \'"+desc+"\'] ]"
objItemFileOutputStream.write(AuthList)
def decrypt ( word ):
if not len(word) > 1: exit()
word = word.replace(':', '')
value1 = binascii.a2b_base64(word)
value2 = '_' * len(value1)
out = ''
for a, b in zip(value1, value2):
out = ''.join([out, chr(ord(a) ^ ord(b))])
return out
#MAIN
search ( AuthAlias, securityFile )
If anyone gets stuck with this issue feel free to post your questions and I will try to answer ASAP.

Configuring grails spring security ldap plugin

here is a part of my perl cgi script (which is working..):
use Net::LDAP;
use Net::LDAP::Entry;
...
$edn = "DC=xyz,DC=com";
$quser ="(&(objectClass=user)(cn=$username))";
$ad = Net::LDAP->new("ip_address...");
$ldap_msg=$ad->bind("$username\#xyz.com", password=>$password);
my $result = $ad->search( base=>$edn,
scope=>"sub",
filter=>$quser);
my $entry;
my $myname;
my $emailad;
my #entries = $result->entries;
foreach $entry (#entries) {
$myname = $entry->get_value("givenName");
$emailad = $entry->get_value("mail");
}
So basically, there is no admin/manager account for AD, users credentials are used for binding. I need to implement the same thing in grails..
+Is there a way to configure the plugin to search several ADs, I know I can add more ldap IPs in context.server but for each server I need a different search base...
++ I dont wanna use my DB, just AD. User logins through ldap > I get his email, and use the email for another ldap query but that will probably be another topic :)
Anyway the code so far is:
grails.plugin.springsecurity.ldap.context.managerDn = ''
grails.plugin.springsecurity.ldap.context.managerPassword = ''
grails.plugin.springsecurity.ldap.context.server = 'ldap://address:389'
grails.plugin.springsecurity.ldap.authorities.ignorePartialResultException = true
grails.plugin.springsecurity.ldap.search.base = 'DC=xyz,DC=com'
grails.plugin.springsecurity.ldap.authenticator.useBind=true
grails.plugin.springsecurity.ldap.authorities.retrieveDatabaseRoles = false
grails.plugin.springsecurity.ldap.search.filter="sAMAccountName={0}"
grails.plugin.springsecurity.ldap.search.searchSubtree = true
grails.plugin.springsecurity.ldap.auth.hideUserNotFoundExceptions = false
grails.plugin.springsecurity.ldap.search.attributesToReturn =
['mail', 'givenName']
grails.plugin.springsecurity.providerNames=
['ldapAuthProvider',anonymousAuthenticationProvider']
grails.plugin.springsecurity.ldap.useRememberMe = false
grails.plugin.springsecurity.ldap.authorities.retrieveGroupRoles = false
grails.plugin.springsecurity.ldap.authorities.groupSearchBase ='DC=xyz,DC=com'
grails.plugin.springsecurity.ldap.authorities.groupSearchFilter = 'member={0}'
And the error code is: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C0906E8, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1
And it's the same code for any user/pass I try :/
Heeeeelp! :)
The most important thing with grails and AD is to use ActiveDirectoryLdapAuthenticationProvider rather than LdapAuthenticationProvider as it will save a world of pain. To do this, just make the following changes:
In resources.groovy:
// Domain 1
ldapAuthProvider1(ActiveDirectoryLdapAuthenticationProvider,
"mydomain.com",
"ldap://mydomain.com/"
)
// Domain 2
ldapAuthProvider2(ActiveDirectoryLdapAuthenticationProvider,
"mydomain2.com",
"ldap://mydomain2.com/"
)
In Config.groovy:
grails.plugin.springsecurity.providerNames = ['ldapAuthProvider1', 'ldapAuthProvider2']
This is all the code you need. You can pretty much remove all other grails.plugin.springsecurity.ldap.* settings in Config.groovy as they don't apply to this AD setup.
Documentation:
http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory

Resources