I have a Powershell app that retrieves some secret data- then needs to execute a .NET exe (locally) passing that data. It appears that passing the data as a raw param could expose it to users on the machine, so I'm looking for a way to keep it secure.
Possible solutions-
Get the data directly from the C# app (possible, but not ideal)
Put the data in an EFS encrypted file and pass the file location
Encrypt the param with a shared key (something built into windows?)
Any tips/guidance would be appreciated.
Please see this Microsoft Technet article:
Working With Passwords and Secure Strings in Windows Powershell
The gist of the above article:
Basic example of encrypting a string:
$PlainParam = "param you want to encrypt"
$SecureParam = $PlainParam | ConvertTo-SecureString -AsPlainText -Force
Cmdlets to look into:
ConvertTo-SecureString
ConvertFrom-SecureString
Related
I'm building a C# desktop application that needs to connects to Azure Ressource Manager. The app must be independent from the Azure Portal.
I need to execute two PowerShell scripts file from C# to create an native application in Azure Active Directory.
the first scipt is :
Import-Module AzureRM.profile
Login-AzureRmAccount
The second is :
$pwd = "{service-principal-password}"
$secureStringPassword = ConvertTo-SecureString -String $pwd -AsPlainText -Force
$azureAdApplication = New-AzureRmADApplication `
-DisplayName $appName `
-HomePage $appHomePage `
-IdentifierUris $appIdentifierUris `
-Password $secureStringPassword
New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Reader `
-ServicePrincipalName $azureAdApplication.ApplicationId.Guid
I have two pass $pwd, $appName, $appHomepage from C# code
Am I on the right way ?? need help
You're getting close to it.
However, there are some tips for your scenario:
The scripts you posted are for creating service principal, not the whole steps for integrating your desktop app.
You can use the ApplicationId in that command:New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $azureAdApplication.ApplicationId
If you want to use powershell to integrate your app, you can refer to these app creation scripts.
You can also refer to this sample to Integrate Azure AD into a Windows desktop application using interactive authentication.
For demonstrates a Desktop daemon application, you can refer to this sample.
Both samples have the application creation powershell scripts.
Please let me know if this helps!
I'm looking to generate ssh keypairs in open SSH format via code within my web-app (hosted in windows machine) instead of having to manually create it using puttygen.
So, far I've not found any free library that can do this. (There doesn't seem to be a ssh-keygen equivalent for windows.) I am aware of the Cygwin route but I'm trying to avoid this as this would involve having to install cygwin on any servers hosting the app making it not ideal.
What are my options? Will I have to extract out the key-gen function from putty-gen-source and re-write it in c#?
RSA rsa = new RSACryptoServiceProvider(2048);
string publicPrivateKeyXML = rsa.ToXmlString(true);
string publicOnlyKeyXML = rsa.ToXmlString(false);
and then you can parse the XML using XML reader or XML document to get the value you want.
I am making one extension for iRedMail server, I want to add new user using C# code.
IrerdMail holding users inside MySQL database, passwords of users are encrypted using openssl (MD5).
When I look at iRedMail api for creating users there is line of code inside bash script:
openssl passwd -1 passwordToBeEncrpted
That command inside terminal return me MD5 string, If I copy that string to my app and execute insert command against MySQL table hosted on mail-server created user works OK.
What will be proper way to generate MD5 from user password so I can insert that to MySQL database ?
My app running on other server beside iRedMAil, Is it obligatory to MD5 be created on the same machine ?
I am considering calling SSH command from C# code , Is there free .NET library which can reuse output stings from SSH as variables ?
Can this be done using something like UDF like in MSSQL server. I know how I cloud call command app from MSSQL does something like that exist at MySQL - CentoOS combination.
Just an idea: instead of trying to call openssl (which users will have to install, or you have to include in your installation procedure) with all the associated hassle it might be preferable to just port over the original C source for crypt.
This will take you some time to get right, but IMO your program will be a lot simpler, more robust and more compact to install.
EDIT: have a look at this question here on SO: Problem porting PHP crypt() function to C# - the code he wrote was meant to be compatible with BSD crypt, so it might be just what you need.. I just tested it in Visual Studio 2010 and compared to the output of openssl on a Linux box here, and the outputs match.
My open-source library CryptSharp (since 2.0) supports MD5 crypt. The syntax is:
string cryptedPassword = Crypter.MD5.Crypt("password");
Should do what you need.
James
I am designing a desktop application in C#, which needs to be connected to my online mysql database. I tried to give access in control panel a "%" which means from any IP, but it is not working. May be the hosting provider (bigrock) not allowing that.
Alternatively, I am trying to write some code in online on PHP which will get the "sql" as parameter and returns the output as JSON format using json_encode.
Is there any alternate methods which is better approach.
What error do you get when you try to connect? Timeout = firewalled; Permission denied = permissions not right etc.
One solution is to create a proxy with pre-coded queries (let's call then "stored procedures") - you can then say "Run query 5, parameters A, B and C". As this would be server-server (not public) you just need to add some basic authentication system (e.g. shared rotating key, checksum using parameters etc), but also ensure the queries are not dangerous if any parameters are thrown at it.
Disclaimer: It's a solution, but I'm not actually recommending that I'd do it unless you're very sure it's safe!
Do you have Cpanel ? If yes, then try adding your host in remote MySQL.
Here the link http://www.liquidweb.com/kb/enable-remote-mysql-connections-in-cpanel/ if you are unsure on how to do that.
I'd advise that you do not create a wildcard user that can connect to the database from anywhere using embedded MySQL credentials in your application. This is a bad idea.
It would be extremely easy to determine the credentials used by your application and then a malicious user could directly connect to your DB server and begin issuing queries to your database.
They will be able to issue SELECT statements for any information in your tables, even info they shouldn't see. It then becomes much easier to exploit any known or unknown vulnerabilities in MySQL much easier since now they have console access and can send data directly to the server. If the account has the DELETE privilege, they can erase all the data in your table(s).
Also, having a PHP script that issues queries provided by the application/end-user is not ideal because one can still freely issue queries. While that option is better than giving blanket access to a remote user, it is still a bad idea.
The way to go would be to identify all of the information that the C# application needs to access, and how, and write a simple web service/API that will receive parameters and issue its own queries and return the results using XML, JSON, or even SOAP. Try to abstract the database access as much as possible from the outside world for the best security.
Hope that helps.
I would do the following:
Create a user with the host of your public ip (www.whatismyip.com).
If that doesn't work, create a user with your host as your public ARPA/PTR record:
>nslookup
> set q=ptr
> 8.8.8.8
Non-authoritative answer:
8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com
8.in-addr.arpa nameserver = ns1.Level3.net
8.in-addr.arpa nameserver = ns2.Level3.net
The host would then be set to google-public-dns-a.google.com.
The second worked, and I am not sure why for me on a project I worked on in the past, where you would have thought the IP address to be sufficient.
I am not sure if you have root access or access to my.cfg. If you can edit it, make sure the line "skip-networking" is commented or removed and it contains line "bind-address = *". Restart mysql after editing config.
For security reasons you shouldn't access the database directly over the (public) network.
One way is to write a php script on the database server and access it via HTTP/POST.
You should authenticate the client via username and a hashed password. The data you are sending should be encrypted (eg with the users clear text password). Don't send complete queries, only what you want to do and the parameters. As example, you want the orders for the customer, you can send a post request with the following parameters
user=abc,password=9151440965cf9c5e07f81eee6241c042a7b78e9bb2dd4f928a8f6da5e369cdffdd2b70c70663ee30d02115731d35f1ece5aad9b362aaa9850efa99e3d197212a,data=EncryptedData
You can notice, that the password is an SHA512 Hash.
The data can be json or anything else:
{
"Command": "GetOrder",
"Limit": "10"
}
In your php code you do the following steps:
1. Authenticate the user, if the password is not correct, respond with error code etc
2. Decrypt the data
3. Execute a query
4. Return the result as encrypted data
If you don't want to store the clear text password in your database, you could store in your database the hashed value and use a double hashed value for authentication and single hashed value for encryption.
If you wan't to execute the queries with parameters from the request you should use prepared statements to prevent sql injection.
More information about en/decrypting in php see: http://php.net/manual/de/ref.mcrypt.php
Like some answers suggested, I think you are firewalled by bigrock.
Now if you want to use AJAX/PHP, you need three things:
- your C# class to send requests and receive the result
- your HTML/JS (or jQuery) file to receive the request and hand it over to your PHP. Then send you the result.
- your PHP file to query your DB.
The AJAX seems superfluous to me, you could just send your query passing it through POST or a GET parameter (i.e. example.com/query.php?req='SELECT * FROM clients')
The code would be as follow:
C# using this class made by Ali Ahsan Rana:
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("http://www.example.com/query.php","POST","req=");
//use System.Web.Script.Serialization and myRequest.GetResponse();
Some tutorial on System.Web.Script.Serialization.
On the PHP side:
<?php
$request=$_POST['req'];
$dsn = 'mysql:dbname=mydb;host=example.com';
$user = 'ajay';
$password = '0000';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$response = $dbh->query($request);
while ($rep = $response->fetch())
{
$response_array[] = $rep;
}
$response->closeCursor();
$return = json_encode($rep);
return($return);
?>
That's a quick draft but should work AFAIK.
I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.
I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.
Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.
Any help would be appreciated,
Bill.
If you use OpenSSH and then have a script to inject password in clear (meaning, you have stored the password unencrypted) it is defeating the purpose of secure shell.
Please strongly consider using public key mechanisms which can be easily and securely automated.
I'll second the recommendation to use public key authentication. Rather than hack around with expect, you might want to consider Paramiko - it's a native SSH client for Python which would greatly simplify the communications process, particularly if you ever need to interact with the remote server and it has support for things like SFTP built-in.
i use pexpect for similar purpose and download also work?
http://sourceforge.net/project/downloading.php?group_id=59762&filename=pexpect-2.3.tar.gz
here is a portion fro my ssh automate script, you can customize it for you usage
it may not run out of the box
import os
import getpass
import pexpect
import glob
import logging
import shutil
import time
class UpdateError(Exception): pass
g_password = None
def runSshCommand(cmd):
global g_password
ssh_newkey = 'Are you sure you want to continue connecting'
# my ssh command line
p=pexpect.spawn(cmd)
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
print "Saying yes to connection.."
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
while True:
if g_password is None:
g_password = getpass.getpass("password:")
p.sendline(g_password)
i = p.expect(['password:',pexpect.EOF])
if i==0:
g_password = None
print "Wrong password"
else:
break
elif i==2:
raise UpdateError("Got key or connection timeout")
return p.before
There is some excellent documentation on using Putty with generated SSH key authentication. This is an easy and secure way to accomplish your goals. Putty has a great set of features, for a windows SSH app. Even better when you consider that you can get it on the free.
pexpect can't import on Windows. So, I use plink.exe with a Python subprocess to connect to the ssh server.
Another way is to to use openssh and establish a trusted key; if both client and the user account on the server have this key, then openssh does not request a password.
I have a script that automates setup of this - it works under cygwin,
http://mosermichael.github.io/cstuff/all/projects/2011/07/14/ssh-friends.html
I hope Net::SSH::Expect Perl module will be of help to you.