File size: 13,312 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the base class from which all SecureString commands
/// are derived.
/// </summary>
public abstract class SecureStringCommandBase : PSCmdlet
{
private SecureString _ss;
/// <summary>
/// Gets or sets the secure string to be used by the get- and set-
/// commands.
/// </summary>
protected SecureString SecureStringData
{
get { return _ss; }
set { _ss = value; }
}
//
// name of this command
//
private readonly string _commandName;
/// <summary>
/// Initializes a new instance of the SecureStringCommandBase
/// class.
/// </summary>
/// <param name="name">
/// The command name deriving from this class
/// </param>
protected SecureStringCommandBase(string name) : base()
{
_commandName = name;
}
private SecureStringCommandBase() : base() { }
}
/// <summary>
/// Defines the base class from which all SecureString import and
/// export commands are derived.
/// </summary>
public abstract class ConvertFromToSecureStringCommandBase : SecureStringCommandBase
{
/// <summary>
/// Initializes a new instance of the ConvertFromToSecureStringCommandBase
/// class.
/// </summary>
protected ConvertFromToSecureStringCommandBase(string name) : base(name) { }
private SecureString _secureKey = null;
private byte[] _key;
/// <summary>
/// Gets or sets the SecureString version of the encryption
/// key used by the SecureString cmdlets.
/// </summary>
[Parameter(Position = 1, ParameterSetName = "Secure")]
public SecureString SecureKey
{
get
{
return _secureKey;
}
set
{
_secureKey = value;
}
}
/// <summary>
/// Gets or sets the byte version of the encryption
/// key used by the SecureString cmdlets.
/// </summary>
[Parameter(ParameterSetName = "Open")]
public byte[] Key
{
get
{
return _key;
}
set
{
_key = value;
}
}
}
/// <summary>
/// Defines the implementation of the 'ConvertFrom-SecureString' cmdlet.
/// This cmdlet exports a new SecureString -- one that represents
/// text that should be kept confidential. The text is encrypted
/// for privacy when being used, and deleted from computer memory
/// when no longer needed. When no key is specified, the command
/// uses the DPAPI to encrypt the string. When a key is specified, the
/// command uses the AES algorithm to encrypt the string.
/// </summary>
[Cmdlet(VerbsData.ConvertFrom, "SecureString", DefaultParameterSetName = "Secure", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096497")]
[OutputType(typeof(string))]
public sealed class ConvertFromSecureStringCommand : ConvertFromToSecureStringCommandBase
{
/// <summary>
/// Initializes a new instance of the ExportSecureStringCommand class.
/// </summary>
public ConvertFromSecureStringCommand() : base("ConvertFrom-SecureString") { }
/// <summary>
/// Gets or sets the secure string to be exported.
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)]
public SecureString SecureString
{
get
{
return SecureStringData;
}
set
{
SecureStringData = value;
}
}
/// <summary>
/// Gets or sets a switch to get the secure string as plain text.
/// </summary>
[Parameter(ParameterSetName = "AsPlainText")]
public SwitchParameter AsPlainText { get; set; }
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command encrypts
/// and exports the object.
/// </summary>
protected override void ProcessRecord()
{
string exportedString = null;
EncryptionResult encryptionResult = null;
const string argumentName = "SecureString";
Utils.CheckSecureStringArg(SecureStringData, argumentName);
if (SecureStringData.Length == 0)
{
throw PSTraceSource.NewArgumentException(argumentName);
}
if (SecureKey != null)
{
Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified");
encryptionResult = SecureStringHelper.Encrypt(SecureString, SecureKey);
}
else if (Key != null)
{
encryptionResult = SecureStringHelper.Encrypt(SecureString, Key);
}
else if (AsPlainText)
{
IntPtr valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(SecureString);
exportedString = Marshal.PtrToStringUni(valuePtr);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
else
{
exportedString = SecureStringHelper.Protect(SecureString);
}
if (encryptionResult != null)
{
// The formatted string is Algorithm Version,
// Initialization Vector, Encrypted Data
string dataPackage = string.Format(
System.Globalization.CultureInfo.InvariantCulture,
"{0}|{1}|{2}",
2,
encryptionResult.IV,
encryptionResult.EncryptedData);
// encode the package, and output it.
// We also include a recognizable prefix so that
// we can use the old decryption mechanism if we
// don't see it. While the old decryption
// generated invalid data for the first bit of the
// SecureString, it at least didn't generate an
// exception.
byte[] outputBytes = System.Text.Encoding.Unicode.GetBytes(dataPackage);
string encodedString = Convert.ToBase64String(outputBytes);
WriteObject(SecureStringHelper.SecureStringExportHeader + encodedString);
}
else if (exportedString != null)
{
WriteObject(exportedString);
}
}
}
/// <summary>
/// Defines the implementation of the 'ConvertTo-SecureString' cmdlet.
/// This cmdlet imports a new SecureString from encrypted data --
/// one that represents text that should be kept confidential.
/// The text is encrypted for privacy when being used, and deleted
/// from computer memory when no longer needed. When no key is
/// specified, the command uses the DPAPI to decrypt the data.
/// When a key is specified, the command uses the AES algorithm
/// to decrypt the data.
/// </summary>
[Cmdlet(VerbsData.ConvertTo, "SecureString", DefaultParameterSetName = "Secure", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096916")]
[OutputType(typeof(SecureString))]
public sealed class ConvertToSecureStringCommand : ConvertFromToSecureStringCommandBase
{
/// <summary>
/// Initializes a new instance of the ImportSecureStringCommand class.
/// </summary>
public ConvertToSecureStringCommand() : base("ConvertTo-SecureString") { }
/// <summary>
/// Gets or sets the unsecured string to be imported.
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)]
public string String
{
get
{
return _s;
}
set
{
_s = value;
}
}
private string _s;
/// <summary>
/// Gets or sets the flag that marks the unsecured string as a plain
/// text string.
/// </summary>
[Parameter(Position = 1, ParameterSetName = "PlainText")]
public SwitchParameter AsPlainText
{
get
{
return _asPlainText;
}
set
{
_asPlainText = value;
}
}
private bool _asPlainText;
/// <summary>
/// Gets or sets the flag that will force the import of a plaintext
/// unsecured string.
/// </summary>
[Parameter(Position = 2, ParameterSetName = "PlainText")]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command decrypts the data,
/// then exports a new SecureString created from the object.
/// </summary>
protected override void ProcessRecord()
{
SecureString importedString = null;
Utils.CheckArgForNullOrEmpty(_s, "String");
try
{
string encryptedContent = String;
byte[] iv = null;
// If this is a V2 package
if (String.StartsWith(SecureStringHelper.SecureStringExportHeader, StringComparison.OrdinalIgnoreCase))
{
try
{
// Trim out the header, and retrieve the
// rest of the string
string remainingData = this.String.Substring(
SecureStringHelper.SecureStringExportHeader.Length,
String.Length - SecureStringHelper.SecureStringExportHeader.Length);
// Unpack it from Base64, get the string
// representation, then parse it into its components.
byte[] inputBytes = Convert.FromBase64String(remainingData);
string dataPackage = System.Text.Encoding.Unicode.GetString(inputBytes);
string[] dataElements = dataPackage.Split('|');
if (dataElements.Length == 3)
{
encryptedContent = dataElements[2];
iv = Convert.FromBase64String(dataElements[1]);
}
}
catch (FormatException)
{
// Will be raised if we can't convert the
// input from a Base64 string. This means
// it's not really a V2 package.
encryptedContent = String;
iv = null;
}
}
if (SecureKey != null)
{
Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified");
importedString = SecureStringHelper.Decrypt(encryptedContent, SecureKey, iv);
}
else if (Key != null)
{
importedString = SecureStringHelper.Decrypt(encryptedContent, Key, iv);
}
else if (!AsPlainText)
{
importedString = SecureStringHelper.Unprotect(String);
}
else
{
importedString = SecureStringHelper.FromPlainTextString(String);
}
}
catch (ArgumentException e)
{
ErrorRecord er =
SecurityUtils.CreateInvalidArgumentErrorRecord(
e,
"ImportSecureString_InvalidArgument"
);
WriteError(er);
}
catch (CryptographicException e)
{
ErrorRecord er =
SecurityUtils.CreateInvalidArgumentErrorRecord(
e,
"ImportSecureString_InvalidArgument_CryptographicError"
);
WriteError(er);
}
if (importedString != null)
{
WriteObject(importedString);
}
}
}
}
|