-
Notifications
You must be signed in to change notification settings - Fork 9
/
Connect-Rsc.cs
306 lines (285 loc) · 13.5 KB
/
Connect-Rsc.cs
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
using System;
using System.Linq;
using System.IO;
using System.Management.Automation;
using System.Security;
using System.Threading.Tasks;
using System.Xml;
using Newtonsoft.Json;
using RubrikSecurityCloud;
using RubrikSecurityCloud.NetSDK.Client;
using RubrikSecurityCloud.NetSDK.Client.Models.Authentication;
using RubrikSecurityCloud.PowerShell.Models;
using RubrikSecurityCloud.PowerShell.Private;
using System.Xml.Linq;
using System.Management.Automation.Runspaces;
using System.Collections;
namespace RubrikSecurityCloud.PowerShell.Cmdlets
{
/// <summary>
/// Establishes a user session with Rubrik Security Cloud
/// </summary>
/// <description>
/// The Connect-Rsc Cmdlet is used to connect to the Rubrik Security Cloud (RSC) API.
/// RSC then returns a unique token to represent the user's credentials for subsequent calls.
/// The token is stored securly in a .NET object within this PowerShell session.
/// The recommended authentication method is a Rsc Service Account.
/// Service Account credentials may be provided as parameters, or stored
/// in an encrypted credential file, using Set-RscServiceAccountFile.
/// Service Account .json files (unencryped) are not supported.
/// </description>
/// <example>
/// Connect to Rubrik Security Cloud, using the URL, Client Id and Client Secret
/// <code>Connect-Rsc -Server mycompany.my.rubrik.com -ClientId xxxxxxxxx -ClientSecret xxxxxxxxx</code>
/// </example>
/// <example>
/// Connect to Rubrik Security Cloud, using a service account file,
/// stored in the default RSC credential store in the user profile
/// The service account file can be downloaded from the Rsc Web UI.
/// <code>
/// Set-RscServiceAccountFile -InputFilePath rubrik_service_account.json
/// Connect-Rsc
/// </code>
/// </example>
/// <example>
/// Connect to Rubrik Security Cloud, using a service account file,
/// stored in a location other than the default RSC credential store.
/// The service account file can be downloaded from the Rsc Web UI.
/// <code>
/// Set-RscServiceAccountFile -InputFilePath rubrik_service_account.json -OutputFilePath rubrik_service_account.xml
/// Connect-Rsc -ServiceAccountFile rubrik_service_account.xml
/// </code>
/// </example>
/// <example>
/// Connect to Rubrik Security Cloud, using a service account file,
/// stored in a location held in the OS environment variable RSC_SERVICE_ACCOUNT_FILE
/// The service account file can be downloaded from the Rsc Web UI.
/// <code>
/// Set-RscServiceAccountFile -InputFilePath rubrik_service_account.json -OutputFilePath $ENV:RSC_SERVICE_ACCOUNT_FILE
/// Connect-Rsc -FromEnv
/// </code>
/// </example>
[Cmdlet(
VerbsCommunications.Connect,
"Rsc",
DefaultParameterSetName = "IfNeeded")]
public class Connect_Rsc : RscBasePSCmdlet
{
/// <summary>
/// Connect if there is no existing connection
/// </summary>
[Parameter(
ParameterSetName = "IfNeeded",
Mandatory = false,
Position = 0,
ValueFromPipeline = false)]
public SwitchParameter IfNeeded { get; set; }
// ----------------------------------------------------------
// Parameter Set "ServiceAccountFileFromEnv"
/// <summary>
/// Use a service account, which path is stored in an environment variable
/// </summary>
[Parameter(
ParameterSetName = "ServiceAccountFileFromEnv",
Mandatory = false,
Position = 0,
ValueFromPipeline = false)]
public SwitchParameter FromEnv { get; set; }
// ----------------------------------------------------------
// Parameter Set "ServiceAccountFile"
/// <summary>
/// Used to specify the service account file downloaded from Rubrik Security Cloud
/// </summary>
[Parameter(
ParameterSetName = "ServiceAccountFile",
Mandatory = true,
Position = 0,
ValueFromPipeline = false)]
public string ServiceAccountFile { get; set; }
// ----------------------------------------------------------
// Parameter Set "ServiceAccountDetails"
/// <summary>
/// FQDN or the Rubrik Security Cloud Instance. I.e. mycompany.my.rubrik.com
/// This can also be found in the JSON file downloaded from RSC when creating the Service Account
/// </summary>
[Parameter(
ParameterSetName = "ServiceAccountDetails",
Mandatory = true,
Position = 0,
ValueFromPipeline = false)]
public string Server { get; set; }
/// <summary>
/// The Service Account ClientId.
/// This can be found as "client_id" in the JSON file downloaded from RSC when creating the Service Account
/// </summary>
[Parameter(
ParameterSetName = "ServiceAccountDetails",
Mandatory = true,
Position = 1,
ValueFromPipeline = false)]
public string ClientId { get; set; }
/// <summary>
/// The Service Account ClientSecret in SecureString format.
/// The ClientSecret can be found as "client_secret" in the JSON file downloaded from RSC when creating the Service Account
/// Convert the JSON plain text field into a secure string with:
/// $secret = $(Get-Content service_account_file.json | ConvertFrom-Json).client_secret | ConvertTo-SecureString -AsPlainText
/// </summary>
[Parameter(
ParameterSetName = "ServiceAccountDetails",
Mandatory = true,
Position = 2,
ValueFromPipeline = false)]
public SecureString ClientSecret { get; set; }
// ----------------------------------------------------------
private string _server;
private string _clientId;
private string _clientSecret;
private bool _doConnect = true;
#pragma warning disable 1591 // ignore warning 'Missing XML comment'
public Connect_Rsc(): base(retrieveConnection: false)
{
}
protected override void BeginProcessing()
{
base.BeginProcessing();
switch (this.ParameterSetName)
{
case "IfNeeded":
{
if (!this.RetrieveConnection(throwIfNotRetrieved: false))
{
goto case "ServiceAccountFile";
}
this._doConnect = false;
this._logger?.Verbose("Already connected. " + this._rbkClient.Info());
return;
}
case "ServiceAccountFileFromEnv":
{
ServiceAccountFile = Environment.GetEnvironmentVariable("RSC_SERVICE_ACCOUNT_FILE");
this.WriteVerbose(
"Retrieving service account file name from " +
"environment variable RSC_SERVICE_ACCOUNT_FILE=" +
ServiceAccountFile);
if (ServiceAccountFile == null)
{
var error = new ErrorRecord(
new ArgumentNullException("Environment variable RSC_SERVICE_ACCOUNT_FILE is not set"),
"ServiceAccountFileFromEnv",
ErrorCategory.InvalidData,
ServiceAccountFile);
ThrowTerminatingError(error);
}
goto case "ServiceAccountFile";
}
case "ServiceAccountFile":
{
try
{
if (String.IsNullOrEmpty(ServiceAccountFile))
{
//ServiceAccountFile option specified, but no file given
//Set the default service account file now
string psProfileDir = this.GetProfileDir();
ServiceAccountFile = Path.Combine(
psProfileDir,
Files.DefaultServiceAccountFileName
);
}
this._logger?.Verbose($"Using Service Account File: {ServiceAccountFile}");
if (!File.Exists(ServiceAccountFile))
{
throw new FileNotFoundException($"Service account file not found: { ServiceAccountFile }." +
$"\nUse Set-RscServiceAccountFile to configure service account authentication.");
}
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create())
{
powerShell.Runspace = runspace;
powerShell.AddCommand("Import-CliXml").AddParameter("Path", ServiceAccountFile);
var saContent = powerShell.Invoke();
foreach(DictionaryEntry entry in saContent[0].BaseObject as Hashtable)
{
switch (entry.Key)
{
case "client_id":
PSCredential clientIdCred = new PSCredential("clientId", (SecureString)entry.Value);
this._clientId = clientIdCred.GetNetworkCredential().Password;
break;
case "client_secret":
PSCredential clientSecretCred = new PSCredential("clientSecret", (SecureString)entry.Value);
this._clientSecret = clientSecretCred.GetNetworkCredential().Password;
break;
case "access_token_uri":
this._server = entry.Value.ToString();
break;
}
}
}
}
}
catch (Exception ex)
{
if (ex.HResult == -2146233087)
{
var error = new ErrorRecord(ex,
"InvalidServiceAccountFileFormat",
ErrorCategory.InvalidData,
ServiceAccountFile);
Console.WriteLine("Connect-Rsc does not support unencrypted JSON files " +
"for service accounts. " +
"Please use the \'Set-RscServiceAccountFile\' cmdlet " +
"to create a valid credential file.");
ThrowTerminatingError(error);
}
else
{
ThrowTerminatingException(
ex,
"CannotOpenOrParseServiceAccountFile",
ErrorCategory.InvalidData,
ServiceAccountFile);
}
}
break;
}
case "ServiceAccountDetails":
{
Console.WriteLine("ServiceAccountDetails");
PSCredential clientSecret = new(ClientId, ClientSecret);
this._server = Server;
this._clientId = ClientId;
this._clientSecret =
clientSecret.GetNetworkCredential().Password;
break;
}
}
this._rbkClient = new RscGraphQLClient(
this._clientId,
this._clientSecret,
this._server,
this._logger);
}
protected override void ProcessRecord()
{
base.ProcessRecord();
if (this._doConnect)
{
if (this.Connect())
{
RscSessionInfo sessionInfo = new RscSessionInfo(
this._rbkClient, new RscLogger(this));
WriteObject(sessionInfo.GetSessionInfo());
}
else
{
this._logger?.Error(
"Failed to connect to Rubrik Security Cloud. " +
this._rbkClient.Info());
}
}
}
}
}