File size: 13,036 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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using Microsoft.PowerShell;
namespace System.Management.Automation
{
/// <summary>
/// Defines the valid types of PSCredentials. Used by PromptForCredential calls.
/// </summary>
[Flags]
public enum PSCredentialTypes
{
/// <summary>
/// Generic credentials.
/// </summary>
Generic = 1,
/// <summary>
/// Credentials valid for a domain.
/// </summary>
Domain = 2,
/// <summary>
/// Default credentials.
/// </summary>
Default = Generic | Domain
}
/// <summary>
/// Defines the options available when prompting for credentials. Used
/// by PromptForCredential calls.
/// </summary>
[Flags]
public enum PSCredentialUIOptions
{
/// <summary>
/// Validates the username, but not its existence
/// or correctness.
/// </summary>
Default = ValidateUserNameSyntax,
/// <summary>
/// Performs no validation.
/// </summary>
None = 0,
/// <summary>
/// Validates the username, but not its existence.
/// or correctness.
/// </summary>
ValidateUserNameSyntax,
/// <summary>
/// Always prompt, even if a persisted credential was available.
/// </summary>
AlwaysPrompt,
/// <summary>
/// Username is read-only, and the user may not modify it.
/// </summary>
ReadOnlyUserName
}
/// <summary>
/// Declare a delegate which returns the encryption key and initialization vector for symmetric encryption algorithm.
/// </summary>
/// <param name="context">The streaming context, which contains the serialization context.</param>
/// <param name="key">Symmetric encryption key.</param>
/// <param name="iv">Symmetric encryption initialization vector.</param>
/// <returns></returns>
public delegate bool GetSymmetricEncryptionKey(StreamingContext context, out byte[] key, out byte[] iv);
/// <summary>
/// Offers a centralized way to manage usernames, passwords, and
/// credentials.
/// </summary>
[Serializable]
public sealed class PSCredential : ISerializable
{
/// <summary>
/// Gets or sets a delegate which returns the encryption key and initialization vector for symmetric encryption algorithm.
/// </summary>
public static GetSymmetricEncryptionKey GetSymmetricEncryptionKeyDelegate
{
get
{
return s_delegate;
}
set
{
s_delegate = value;
}
}
private static GetSymmetricEncryptionKey s_delegate = null;
/// <summary>
/// GetObjectData.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
return;
// serialize the secure string
string safePassword = string.Empty;
if (_password != null && _password.Length > 0)
{
byte[] key;
byte[] iv;
if (s_delegate != null && s_delegate(context, out key, out iv))
{
safePassword = SecureStringHelper.Encrypt(_password, key, iv).EncryptedData;
}
else
{
try
{
safePassword = SecureStringHelper.Protect(_password);
}
catch (CryptographicException cryptographicException)
{
throw PSTraceSource.NewInvalidOperationException(cryptographicException, Credential.CredentialDisallowed);
}
}
}
info.AddValue("UserName", _userName);
info.AddValue("Password", safePassword);
}
/// <summary>
/// PSCredential.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
private PSCredential(SerializationInfo info, StreamingContext context)
{
if (info == null)
return;
_userName = (string)info.GetValue("UserName", typeof(string));
// deserialize to secure string
string safePassword = (string)info.GetValue("Password", typeof(string));
if (safePassword == string.Empty)
{
_password = new SecureString();
}
else
{
byte[] key;
byte[] iv;
if (s_delegate != null && s_delegate(context, out key, out iv))
{
_password = SecureStringHelper.Decrypt(safePassword, key, iv);
}
else
{
_password = SecureStringHelper.Unprotect(safePassword);
}
}
}
private readonly string _userName;
private readonly SecureString _password;
/// <summary>
/// User's name.
/// </summary>
public string UserName
{
get { return _userName; }
}
/// <summary>
/// User's password.
/// </summary>
public SecureString Password
{
get { return _password; }
}
/// <summary>
/// Initializes a new instance of the PSCredential class with a
/// username and password.
/// </summary>
/// <param name="userName">User's name.</param>
/// <param name="password">User's password.</param>
public PSCredential(string userName, SecureString password)
{
Utils.CheckArgForNullOrEmpty(userName, "userName");
Utils.CheckArgForNull(password, "password");
_userName = userName;
_password = password;
}
/// <summary>
/// Initializes a new instance of the PSCredential class with a
/// username and password from PSObject.
/// </summary>
/// <param name="pso"></param>
public PSCredential(PSObject pso)
{
if (pso == null)
throw PSTraceSource.NewArgumentNullException(nameof(pso));
if (pso.Properties["UserName"] != null)
{
_userName = (string)pso.Properties["UserName"].Value;
if (pso.Properties["Password"] != null)
_password = (SecureString)pso.Properties["Password"].Value;
}
}
/// <summary>
/// Initializes a new instance of the PSCredential class.
/// </summary>
private PSCredential()
{
}
private NetworkCredential _netCred;
/// <summary>
/// Returns an equivalent NetworkCredential object for this
/// PSCredential.
///
/// A null is returned if
/// -- current object has not been initialized
/// -- current creds are not compatible with NetworkCredential
/// (such as smart card creds or cert creds)
/// </summary>
/// <returns>
/// null if the current object has not been initialized.
/// null if the current credentials are incompatible with
/// a NetworkCredential -- such as smart card credentials.
/// the appropriate network credential for this PSCredential otherwise.
/// </returns>
public NetworkCredential GetNetworkCredential()
{
if (_netCred == null)
{
string user = null;
string domain = null;
if (IsValidUserName(_userName, out user, out domain))
{
_netCred = new NetworkCredential(user, _password, domain);
}
}
return _netCred;
}
/// <summary>
/// Provides an explicit cast to get a NetworkCredential
/// from this PSCredential.
/// </summary>
/// <param name="credential">PSCredential to convert.</param>
/// <returns>
/// null if the current object has not been initialized.
/// null if the current credentials are incompatible with
/// a NetworkCredential -- such as smart card credentials.
/// the appropriate network credential for this PSCredential otherwise.
/// </returns>
public static explicit operator NetworkCredential(PSCredential credential)
{
#pragma warning disable 56506
if (credential == null)
{
throw PSTraceSource.NewArgumentNullException("credential");
}
return credential.GetNetworkCredential();
#pragma warning restore 56506
}
/// <summary>
/// Gets an empty PSCredential. This is an PSCredential with both UserName
/// and Password initialized to null.
/// </summary>
public static PSCredential Empty
{
get
{
return s_empty;
}
}
private static readonly PSCredential s_empty = new PSCredential();
/// <summary>
/// Parse a string that represents a fully qualified username
/// to verify that it is syntactically valid. We only support
/// two formats:
/// -- domain\user
/// -- user@domain
///
/// for any other format, we simply treat the entire string
/// as user name and set domain name to "".
/// </summary>
private static bool IsValidUserName(string input,
out string user,
out string domain)
{
if (string.IsNullOrEmpty(input))
{
user = domain = null;
return false;
}
SplitUserDomain(input, out user, out domain);
if ((user == null) ||
(domain == null) ||
(user.Length == 0))
{
// UserName is the public property of Credential object. Use this as
// parameter name in error
// See bug NTRAID#Windows OS Bugs-1106386-2005/03/25-hiteshr
throw PSTraceSource.NewArgumentException("UserName", Credential.InvalidUserNameFormat);
}
return true;
}
/// <summary>
/// Split a given string into its user and domain
/// components. Supported formats are:
/// -- domain\user
/// -- user@domain
///
/// With any other format, the entire input is treated as user
/// name and domain is set to "".
///
/// In any case, the function does not check if the split string
/// are really valid as user or domain names.
/// </summary>
private static void SplitUserDomain(string input,
out string user,
out string domain)
{
int i = 0;
user = null;
domain = null;
if ((i = input.IndexOf('\\')) >= 0)
{
user = input.Substring(i + 1);
domain = input.Substring(0, i);
return;
}
// In V1 and V2, we had a bug where email addresses (i.e. foo@bar.com)
// were being split into Username=Foo, Domain=bar.com.
//
// This was breaking apps (i.e.: Exchange), so we need to make
// Username = foo@bar.com if the domain has a dot in it (since
// domains can't have dots).
//
// HOWEVER, there was a workaround for this bug in v1 and v2, where the
// cred could be entered as "foo@bar.com@bar.com" - making:
// Username = foo@bar.com, Domain = bar.com
//
// We need to keep the behaviour in this case.
i = input.LastIndexOf('@');
if (
(i >= 0) &&
(
(input.LastIndexOf('.') < i) ||
(input.IndexOf('@') != i)
)
)
{
domain = input.Substring(i + 1);
user = input.Substring(0, i);
}
else
{
user = input;
domain = string.Empty;
}
}
}
}
|