-
Notifications
You must be signed in to change notification settings - Fork 1
/
PureStorage.Pure1.psm1
3168 lines (2886 loc) · 123 KB
/
PureStorage.Pure1.psm1
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Get-PureOneCertificate {
<#
.SYNOPSIS
Returns the Windows Certificate or RSA Private Key used for Pure1 Authentication.
.DESCRIPTION
Returns the default Pure1 certificate or key. Or returns the specified certificate object if a non-default one is used.
.INPUTS
Certificate store (optional), certificate thumbrint (optional)
.OUTPUTS
Returns the certificate object or private key path
.EXAMPLE
PS C:\ Get-PureOneCertificate
Returns the default Pure1 certificate in the default certificiate store cert:\currentuser\my or the Default Private Key path if using Linux or MacOS
.EXAMPLE
PS C:\ Get-PureOneCertificate -certificateStore cert:\localmachine\my
Windows only: Returns the default Pure1 certificate in the certificiate store cert:\localmachine\my
.EXAMPLE
PS C:\ Get-PureOneCertificate -CertificateThumbprint 3ED3EB9BF753849820CFF43B2444100D334B60DD
Windows only: Returns the Pure1 certificate with the specified thumbprint in the default certificiate store cert:\currentuser\my
.EXAMPLE
PS C:\ Get-PureOneCertificate -certificateStore cert:\localmachine\my -CertificateThumbprint 3ED3EB9BF753849820CFF43B2444100D334B60DD
Windows only: Returns the Pure1 certificate with the specified thumbprint in the specified certificiate store
.EXAMPLE
PS C:\ $password = Read-Host -AsSecureString
PS C:\ Get-PureOneCertificate -export -CertificatePassword $password
Will export the certificate to a PFX file with the specified password. Returns the file path.
.EXAMPLE
PS C:\ $password = Read-Host -AsSecureString
PS C:\ Get-PureOneCertificate -export -CertificatePassword $password -exportdirectory C:\Users\Pureuser\Certs
Will export the certificate to a PFX file in the specified directory with the specified password. Returns the file path.
.NOTES
Version: 1.1
Author: Cody Hosterman https://codyhosterman.com
Creation Date: 12/05/2020
Purpose/Change: Initial Release
*******Disclaimer:******************************************************
This scripts are offered "as is" with no warranty. While this
scripts is tested and working in my environment, it is recommended that you test
this script in a test lab before using in a production environment. Everyone can
use the scripts/commands provided here without any written permission but I
will not be liable for any damage or loss to the system.
************************************************************************
#>
[CmdletBinding()]
Param(
[Parameter(Position=0)]
[String]$CertificateStore,
[Parameter(Position=1)]
[String]$CertificateThumbprint,
[Parameter(Position=2,ParameterSetName='Export')]
[Switch]$Export,
[Parameter(Position=3,ParameterSetName='Export')]
[SecureString]$CertificatePassword,
[Parameter(Position=4,ParameterSetName='Export')]
[String]$ExportDirectory
)
if (($IsLinux -eq $true) -or ($IsMacOS -eq $true))
{
if ($Export -eq $true)
{
throw "Export is only valid for Windows."
}
}
if ($IsWindows -eq $false)
{
if (![string]::IsNullOrEmpty($CertificateStore))
{
throw "The use of the CertificateStore parameter is only valid for Windows."
}
if (![string]::IsNullOrEmpty($CertificateThumbprint))
{
throw "The use of the CertificateThumbprint parameter is only valid for Windows."
}
$PrivateKeyFilePath = (Get-Location).Path + "/PureOnePrivate.pem"
$checkPath = Test-Path $PrivateKeyFilePath
if ($checkPath -eq $true)
{
return $PrivateKeyFilePath
}
else {
throw "Key not found at the default location of $($PrivateKeyFilePath). Please create a new one with New-PureOneCertificate. If a custom path is used, there is no need for this cmdlet. Instead specify the custom path for subsequent cmds."
}
}
else {
if ([string]::IsNullOrEmpty($CertificateStore))
{
$CertificateStore = "cert:\currentuser\my"
}
if ([string]::IsNullOrEmpty($CertificateThumbprint))
{
$cert = Get-ChildItem -Path $CertificateStore |where-object {$_.FriendlyName -eq "Default Pure1 REST API Certificate"}
if ($cert.Count -gt 1)
{
throw "More than one default certificate was found in the specified certificate store (a certificate that has the friendly name of `"Default Pure1 REST API Certificate`")."
}
if ($null -eq $cert)
{
throw "No default certificate found in the specified certificate store (a certificate that has the friendly name of `"Default Pure1 REST API Certificate`")."
}
}
else {
$cert = Get-ChildItem -Path ($CertificateStore + "\" + $CertificateThumbprint) -ErrorAction Stop
}
}
if ($Export -eq $true)
{
if ($null -eq $CertificatePassword)
{
do {
$CertificatePassword = Read-Host "Please enter a certificate export password" -AsSecureString
}while ($CertificatePassword.length -eq 0)
}
if ([string]::IsNullOrEmpty($ExportDirectory))
{
$keyPath = (Get-Location).Path
}
else {
if ((Test-Path -Path $ExportDirectory) -eq $false)
{
throw "Entered path $($ExportDirectory) is not valid. Please enter a valid directory. For example, C:\Users\Janice\Certs"
}
else {
$keyPath = $ExportDirectory
}
}
if ($PSVersionTable.PSEdition -ne "Core")
{
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($CertificatePassword)
$DecryptedCertificatePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
}
else {
$DecryptedCertificatePassword = ConvertFrom-SecureString $CertificatePassword -AsPlainText
}
$cert |Foreach-Object { [system.IO.file]::WriteAllBytes("$($keyPath)\PureOneCert.pfx",($_.Export('PFX', $DecryptedCertificatePassword)) ) }
$foundKey = test-path "$($keyPath)\PureOneCert.pfx"
if ($foundKey -eq $true)
{
return "$($keyPath)\PureOneCert.pfx"
}
else {
throw "The certificate could not be exported to $($keyPath)\PureOneCert.pfx. Ensure directory is accessible."
}
}
else {
return $cert
}
}
function Set-PureOneDefaultCertificate {
<#
.SYNOPSIS
Set a Windows Certificate to the default certificate used for Pure1 Authentication.
.DESCRIPTION
The default certificate is designated by using the friendly name of Default Pure1 REST API Certificate
.INPUTS
Certificate, or certificate store and certificate thumbprint
.OUTPUTS
Returns the certificate object
.EXAMPLE
PS C:\ Set-PureOneDefaultCertificate -certificateStore cert:\localmachine\my -CertificateThumbprint 3ED3EB9BF753849820CFF43B2444100D334B60DD
Set the specified certificate to the default.
.EXAMPLE
PS C:\ $cert = Get-ChildItem -Path cert:\localmachine\my\3ED3EB9BF753849820CFF43B2444100D334B60DD
PS C:\ $cert | Set-PureOneDefaultCertificate
Set the specified certificate to the default.
.EXAMPLE
PS C:\ $cert = Get-ChildItem -Path cert:\localmachine\my\3ED3EB9BF753849820CFF43B2444100D334B60DD
PS C:\ $cert | Set-PureOneDefaultCertificate -Confirm:$false
Set the specified certificate to the default without prompt
.NOTES
Version: 1.0
Author: Cody Hosterman https://codyhosterman.com
Creation Date: 11/11/2020
Purpose/Change: Initial Release
*******Disclaimer:******************************************************
This scripts are offered "as is" with no warranty. While this
scripts is tested and working in my environment, it is recommended that you test
this script in a test lab before using in a production environment. Everyone can
use the scripts/commands provided here without any written permission but I
will not be liable for any damage or loss to the system.
************************************************************************
#>
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
Param(
[Parameter(Position=0,ValueFromPipeline=$True,mandatory=$True,ParameterSetName='Certificate')]
[System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate,
[Parameter(Position=0,ParameterSetName='Thumbprint')]
[String]$CertificateStore,
[Parameter(Position=1,mandatory=$True,ParameterSetName='Thumbprint')]
[String]$CertificateThumbprint
)
Begin {
$checkForOneCert = $false
if (($IsLinux -eq $true) -or ($IsMacOS -eq $true))
{
throw "This cmdlet is only valid/relevant for Windows-based installations of PowerShell."
}
}
Process {
if ($checkForOneCert -eq $false)
{
$checkForOneCert = $True
}
else {
throw "Please only pass in one certificate at a time. More than one found in the pipelined input for parameter Certificate."
}
}
End {
if ([string]::IsNullOrEmpty($CertificateStore))
{
$CertificateStore = "cert:\currentuser\my"
}
if ([string]::IsNullOrEmpty($Certificate))
{
$Certificate = Get-ChildItem -Path ($CertificateStore + "\" + $CertificateThumbprint) -ErrorAction Stop
}
$certs = Get-ChildItem -Path $Certificate.PSParentPath
foreach ($eachCert in $certs)
{
if ($Certificate.Thumbprint -eq $eachCert.Thumbprint)
{
continue
}
if ($eachCert.FriendlyName -eq "Default Pure1 REST API Certificate")
{
$foundCert = $eachCert
break
}
}
if ($null -ne $foundCert)
{
$confirmText = "A default certificate is already found with the thumbprint of $($foundCert.Thumbprint). Remove this certificate as default and set $($Certificate.Thumbprint) as the default?"
if ($PSCmdlet.ShouldProcess("","$($confirmText)`n`r","Setting $($Certificate.Thumbprint) as the default. `n`r"))
{
(Get-ChildItem -Path $foundCert.PSPath).FriendlyName = $null |Out-Null
((Get-ChildItem -Path $Certificate.PSPath).FriendlyName = "Default Pure1 REST API Certificate") |Out-Null
return $Certificate
}
}
else {
((Get-ChildItem -Path $Certificate.PSPath).FriendlyName = "Default Pure1 REST API Certificate") |Out-Null
return $Certificate
}
}
}
function New-PureOneCertificate {
<#
.SYNOPSIS
Creates a new certificate for use in authentication with Pure1.
.DESCRIPTION
Creates a properly formatted RSA 256 certificate
.INPUTS
Certificate store (optional)
.OUTPUTS
Returns the certificate
.EXAMPLE
PS C:\ New-PureOneCertificate
Creates a properly formatted self-signed certificate for Pure1 authentication. Defaults to certificate store of cert:\currentuser\my
.EXAMPLE
PS C:\ New-PureOneCertificate -NonDefault
Creates a properly formatted self-signed certificate for Pure1 authentication. Defaults to certificate store of cert:\currentuser\my. The nonDefault switch makes the created certificate not the default one.
.EXAMPLE
PS C:\ New-PureOneCertificate -certificateStore cert:\localmachine\my
Creates a properly formatted self-signed certificate for Pure1 authentication. Uses the specifed certificate store. Non-default stores usually require running as administrator. Windows only.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> New-PureOneCertificate -RsaPassword $password
Creates a properly formatted private and public key pair for Pure1 authentication. Uses the working directory. Linux or MacOS only.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> New-PureOneCertificate -RsaPassword $password -PrivateKeyFileDirectory "/home/pureuser"
Creates a properly formatted private and public key pair for Pure1 authentication and stores it in specified directory. Linux or MacOS only.
.NOTES
Version: 1.1
Author: Cody Hosterman https://codyhosterman.com
Creation Date: 08/29/2020
Purpose/Change: Core support
*******Disclaimer:******************************************************
This scripts are offered "as is" with no warranty. While this
scripts is tested and working in my environment, it is recommended that you test
this script in a test lab before using in a production environment. Everyone can
use the scripts/commands provided here without any written permission but I
will not be liable for any damage or loss to the system.
************************************************************************
#>
[CmdletBinding(DefaultParameterSetName='Certificate')]
Param(
[Parameter(Position=0,ParameterSetName='Certificate')]
[Parameter(Position=0,ParameterSetName='Import')]
[String]$CertificateStore = "cert:\currentuser\my",
[Parameter(Position=1,ParameterSetName='RSAPair')]
[SecureString]$RsaPassword,
[Parameter(Position=2,ParameterSetName='RSAPair',mandatory=$True)]
[Parameter(Position=2,ParameterSetName='Import')]
[SecureString]$Password,
[Parameter(Position=3)]
[Switch]$Overwrite,
[Parameter(Position=4,ParameterSetName='RSAPair')]
[String]$PrivateKeyFileDirectory,
[Parameter(Position=5,ParameterSetName='Certificate')]
[Parameter(Position=5,ParameterSetName='Import')]
[Switch]$NonDefault,
[Parameter(Position=6,ParameterSetName='Import',mandatory=$True)]
[String]$CertificateFile
)
if (![string]::IsNullOrEmpty($CertificateFile))
{
if (($IsMacOS -eq $true) -or ($IsLinux -eq $true))
{
throw "Import feature is only valid for Windows environments."
}
$checkFile = Test-Path $CertificateFile
if ($checkFile -eq $false)
{
throw "$($certificateFile) is not found. Please confirm file path is correct."
}
$certExtension = [IO.Path]::GetExtension($CertificateFile)
if ($certExtension -ne ".pfx")
{
throw "The certificate should be a pfx file. File type found is $($certExtension)"
}
if ($Password.Length -eq 0)
{
$Password = Read-Host -Prompt "Please enter a password to be used for the private key" -AsSecureString
}
$ErrorActionPreference = "Stop"
$CertObj = Import-PfxCertificate -FilePath $CertificateFile -CertStoreLocation $CertificateStore -Password $Password -Exportable -ErrorAction Stop
}
if ($IsWindows -eq $false)
{
if ([string]::IsNullOrEmpty($PrivateKeyFileDirectory))
{
$keyPath = (Get-Location).Path
}
else {
if ((Test-Path -Path $PrivateKeyFileDirectory) -eq $false)
{
throw "Entered path $($PrivateKeyFileDirectory) is not valid. Please enter a valid directory. For example, /home/user"
}
else {
$keyPath = $PrivateKeyFileDirectory
}
}
$checkPath = Test-Path "$($keyPath)/PureOnePrivate.pem"
if (($checkPath -eq $true) -and ($Overwrite -eq $false))
{
throw "A pre-existing Pure1 Private Key exists at $($keyPath)/PureOnePrivate.pem. Overwriting this key will require a new application ID to be generated for the new key in Pure1. Either re-run with the -overwrite switch, or specify a different directory in the -keypath parameter, or skip this cmdlet and pass in the path of your custom key location to New-PureOneConnection."
}
if ($Password.Length -eq 0)
{
if ($RsaPassword.Length -eq 0)
{
$Password = Read-Host -Prompt "Please enter a password to be used for the private key" -AsSecureString
}
else {
Write-Warning "The RsaPassword parameter is being deprecated. Please use the Password parameter instead."
$Password = $RsaPassword
}
}
$DecryptedPassword = ConvertFrom-SecureString $Password -AsPlainText
if (($DecryptedPassword.length -lt 4) -or ($DecryptedPassword.length -gt 1022))
{
throw "The entered private key password must be more than 4 characters and less than 1023 characters."
}
openssl genrsa -aes256 -passout pass:$DecryptedPassword -out $keypath/PureOnePrivate.pem 2048 2>/dev/null
openssl rsa -in $keypath/PureOnePrivate.pem -outform PEM -pubout -out $keypath/PureOnePublic.pem -passin pass:$DecryptedPassword 2>/dev/null
$keyPaths = [ordered]@{
PrivateKey = "$($keyPath)/PureOnePrivate.pem"
PublicKey = "$($keyPath)/PureOnePublic.pem"
}
return $keyPaths
}
if (($null -eq $isWindows) -or ($isWindows -eq $true))
{
if ([string]::IsNullOrEmpty($CertificateFile))
{
if (([System.Environment]::OSVersion.Version).Major -eq 6)
{
#For Windows 2012 support--less specific but the default certificate still works.
$CertObj = New-SelfSignedCertificate -certstorelocation $certificateStore -DnsName PureOneCert
}
else
{
$policies = [System.Security.Cryptography.CngExportPolicies]::AllowPlaintextExport,[System.Security.Cryptography.CngExportPolicies]::AllowExport
$CertObj = New-SelfSignedCertificate -certstorelocation $certificateStore -HashAlgorithm "SHA256" -KeyLength 2048 -KeyAlgorithm RSA -KeyUsage DigitalSignature -KeyExportPolicy $policies -Subject "PureOneCert" -ErrorAction Stop
}
}
$cert = Get-ChildItem -Path $CertObj.PSPath
if ($NonDefault -eq $false)
{
$certs = Get-ChildItem -Path $cert.PSParentPath
foreach ($eachCert in $certs)
{
if ($cert.Thumbprint -eq $eachCert.Thumbprint)
{
continue
}
if ($eachCert.FriendlyName -eq "Default Pure1 REST API Certificate")
{
$foundCert = $eachCert
break
}
}
if (($null -ne $foundCert) -and ($Overwrite -ne $true))
{
$cert = Set-PureOneDefaultCertificate -Certificate $cert -Confirm:$true
}
else {
$cert = Set-PureOneDefaultCertificate -Certificate $cert -Confirm:$false
}
}
return $cert
}
}
function Get-PureOnePublicKey {
<#
.SYNOPSIS
Retrives and formats a PEM based Public Key from a Windows-based certificate
.DESCRIPTION
Pulls out the public key and formats it in INT 64 PEM encoding for use in Pure1
.INPUTS
Certificate
.OUTPUTS
Returns the PEM based public key
.EXAMPLE
PS C:\ Get-PureOnePublicKey
Returns the PEM formatted Public Key of the default certificate.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> Get-PureOnePublicKey -RsaPassword $password
Returns the PEM formatted Public Key of the default private key.
.EXAMPLE
PS C:\ $cert = New-PureOneCertificate
PS C:\ Get-PureOnePublicKey -certificate $cert
Returns the PEM formatted Public Key of the certificate passed in so that it can be entered in Pure1.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> $keys = New-PureOneCertificate -RsaPassword $password
PS /home/pureuser> Get-PureOnePublicKey -PrivateKeyFileLocation $keys.PrivateKey -RsaPassword $password
Returns the PEM formatted Public Key of the default Pure1 private key file passed in so that it can be entered in Pure1.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> Get-PureOnePublicKey -PrivateKeyFileLocation /home/pureuser/PureOnePrivateKey.pem -RsaPassword $password
Returns the PEM formatted Public Key of a private key file passed in so that it can be entered in Pure1.
.NOTES
Version: 1.1
Author: Cody Hosterman https://codyhosterman.com
Creation Date: 08/29/2020
Purpose/Change: Core support
*******Disclaimer:******************************************************
This scripts are offered "as is" with no warranty. While this
scripts is tested and working in my environment, it is recommended that you test
this script in a test lab before using in a production environment. Everyone can
use the scripts/commands provided here without any written permission but I
will not be liable for any damage or loss to the system.
************************************************************************
#>
[CmdletBinding(DefaultParameterSetName='Certificate')]
Param(
[Parameter(Position=0,ValueFromPipeline=$True,ParameterSetName='Certificate')]
[System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate,
[Parameter(Position=1,ParameterSetName='RSAPair')]
[String]$PrivateKeyFileLocation,
[Parameter(Position=2,ParameterSetName='RSAPair')]
[securestring]$RsaPassword
)
Begin {
$publicKeys = @()
}
Process {
if (($IsLinux -eq $true) -or ($IsMacOS -eq $true))
{
if ([string]::IsNullOrEmpty($PrivateKeyFileLocation))
{
$PrivateKeyFileLocation = Get-PureOneCertificate -ErrorAction SilentlyContinue
}
if ([string]::IsNullOrEmpty($PrivateKeyFileLocation))
{
throw "No private key provided and default key does not exist. Please provide a private key path or create a new one."
}
if ($RsaPassword.length -eq 0)
{
do {
$RsaPassword = Read-Host "Please enter your RSA private key password" -AsSecureString
} while ($RsaPassword.length -eq 0)
}
$checkPath = Test-Path $PrivateKeyFileLocation
if ($checkPath -eq $false)
{
throw "File not found at $($PrivateKeyFileLocation). Check path and try again."
}
$DecryptedRsaPassword = ConvertFrom-SecureString $RsaPassword -AsPlainText
openssl rsa -in $($PrivateKeyFileLocation) -outform PEM -pubout -out ./PureOnePublicTemp.pem -passin pass:$DecryptedRsaPassword 2>/dev/null
$checkPath = Test-Path ./PureOnePublicTemp.pem
if ($checkPath -eq $false)
{
throw "Public key could not be generated. Confirm password and/or permission access to private key"
}
$publicKey = Get-Content ./PureOnePublicTemp.pem
Remove-Item -Path ./PureOnePublicTemp.pem
$publicKeys += $publicKey
}
else {
if ($null -eq $certificate)
{
$Certificate = Get-PureOneCertificate -ErrorAction SilentlyContinue
if ($null -eq $certificate)
{
throw "You must pass in a x509 certificate or create/set a default one."
}
}
$certRaw = ([System.Convert]::ToBase64String($certificate.PublicKey.EncodedKeyValue.RawData)).tostring()
$publicKeys += ("-----BEGIN PUBLIC KEY-----`n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A" + $certRaw + "`n-----END PUBLIC KEY-----")
}
}
End {
return $publicKeys
}
}
function New-PureOneJwt {
<#
.SYNOPSIS
Takes in a Pure1 Application ID and certificate to create a JSON Web Token.
.DESCRIPTION
Takes in a Pure1 Application ID and certificate to create a JSON Web Token that is valid for by default 30 days, but is extended if a custom expiration is passed in. Can also take in a private key in lieu of the full cert. Will reject if the private key is not properly formatted.
.INPUTS
Pure1 Application ID, an expiration, and a certificate or a private key.
.OUTPUTS
Returns the JSON Web Token as a string.
.EXAMPLE
PS C:\ New-PureOneJwt -pureAppID pure1:apikey:v4u3ZXXXXXXXXC6o
Returns a JSON Web Token that can be used to create a Pure1 REST session. A JWT generated with no specificed expiration is valid for 30 days. Since no certificate is specified it will use the default certificate if it exists.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> New-PureOneJwt -RsaPassword $password -PureAppID pure1:apikey:TACAwKsXL7kLa96q
Returns a JSON Web Token that can be used to create a Pure1 REST session. A JWT generated with no specificed expiration is valid for 30 days. Since no key file is specified it will use the default key file if it exists.
.EXAMPLE
PS C:\ $cert = New-PureOneCertificate
PS C:\ New-PureOneJwt -certificate $cert -pureAppID pure1:apikey:v4u3ZXXXXXXXXC6o
Returns a JSON Web Token that can be used to create a Pure1 REST session. A JWT generated with no specificed expiration is valid for 30 days.
.EXAMPLE
PS C:\ $cert = New-PureOneCertificate
PS C:\ New-PureOneJwt -certificate $cert -pureAppID pure1:apikey:v4u3ZXXXXXXXXC6o -expiration ((get-date).addDays(2))
Returns a JSON Web Token that can be used to create a Pure1 REST session. An expiration is set for two days from now, so this JWT will be valid to create new REST sessions for 48 hours.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> New-PureOneJwt -PrivateKeyFileLocation /home/pureuser/PureOnePrivate.pem -RsaPassword $password -PureAppID pure1:apikey:TACAwKsXL7kLa96q
Creates a JSON web token for external use for the specified private key and the associated Pure1 API key.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> New-PureOneJwt -PrivateKeyFileLocation /home/pureuser/PureOnePrivate.pem -RsaPassword $password -PureAppID pure1:apikey:TACAwKsXL7kLa96q
Creates a JSON web token for external use for the specified private key and the associated Pure1 API key. An expiration is set for two days from now, so this JWT will be valid to create new REST sessions for 48 hours.
.NOTES
Version: 1.2
Author: Cody Hosterman https://codyhosterman.com
Creation Date: 12/05/2020
Purpose/Change: Improved interactions
*******Disclaimer:******************************************************
This scripts are offered "as is" with no warranty. While this
scripts is tested and working in my environment, it is recommended that you test
this script in a test lab before using in a production environment. Everyone can
use the scripts/commands provided here without any written permission but I
will not be liable for any damage or loss to the system.
************************************************************************
#>
[CmdletBinding(DefaultParameterSetName='None')]
Param(
[Parameter(Position=0,ValueFromPipeline=$True,ParameterSetName='WindowsCert')]
[System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate,
[Parameter(Position=1,mandatory=$True,ParameterSetName='WindowsCert')]
[Parameter(Position=1,mandatory=$True,ParameterSetName='WindowsKey')]
[Parameter(Position=1,mandatory=$True,ParameterSetName='Unix')]
[Parameter(Position=1,mandatory=$True,ParameterSetName='None')]
[string]$PureAppID,
[Parameter(Position=2,ParameterSetName='WindowsKey')]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(Position=3,ParameterSetName='WindowsCert')]
[Parameter(Position=3,ParameterSetName='WindowsKey')]
[Parameter(Position=3,ParameterSetName='Unix')]
[Parameter(Position=3,ParameterSetName='None')]
[System.DateTime]$Expiration,
[Parameter(Position=4,ParameterSetName='Unix')]
[string]$PrivateKeyFileLocation,
[Parameter(Position=5,ParameterSetName='Unix',mandatory=$True)]
[securestring]$RsaPassword
)
Begin {
$checkForOneCert = $false
}
Process {
if ($checkForOneCert -eq $false)
{
$checkForOneCert = $True
}
else {
throw "Please only pass in one certificate at a time. More than one found in the pipelined input for parameter Certificate."
}
}
End {
if (($IsLinux -eq $true) -or ($IsMacOS -eq $true))
{
if ([string]::IsNullOrEmpty($PrivateKeyFileLocation))
{
$PrivateKeyFileLocation = Get-PureOneCertificate -ErrorAction SilentlyContinue
}
if ([string]::IsNullOrEmpty($PrivateKeyFileLocation))
{
throw "No private key provided and default key does not exist. Please provide a private key path or create a new one."
}
}
if (($null -eq $isWindows) -or ($isWindows -eq $true))
{
if (($null -eq $privateKey) -and ($null -eq $certificate))
{
$Certificate = Get-PureOneCertificate -ErrorAction SilentlyContinue
if ($null -eq $certificate)
{
throw "You must pass in a x509 certificate or a RSA Private Key"
}
}
#checking for certificate accuracy
if ($null -ne $certificate)
{
if ($certificate.HasPrivateKey -ne $true)
{
throw "There is no private key associated with this certificate. Please regenerate certificate with a private key."
}
if ($null -ne $certificate.PrivateKey)
{
$privateKey = $certificate.PrivateKey
}
else {
try {
$privateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
}
catch {
throw "Could not obtain the private key from the certificate. Please re-run this cmdlet from a PowerShell session started with administrative rights or ensure you have Read Only or higher rights to the certificate."
}
}
}
#checking for correct private key type. Must be SHA-256, 2048 bit.
if ($null -ne $privateKey)
{
if ($privateKey.KeySize -ne 2048)
{
throw "The key must be 2048 bit. It is currently $($privateKey.KeySize)"
}
if ($privateKey.SignatureAlgorithm -ne "RSA")
{
throw "This key is not an RSA-based key."
}
}
}
$pureHeader = '{"alg":"RS256","typ":"JWT"}'
$curTime = (Get-Date).ToUniversalTime()
$curTime = [Math]::Floor([decimal](Get-Date($curTime) -UFormat "%s"))
if ($null -eq $expiration)
{
$expTime = $curTime + 2592000
}
else {
$expTime = $expiration.ToUniversalTime()
$expTime = [Math]::Floor([decimal](Get-Date($expTime) -UFormat "%s"))
}
$payloadJson = '{"iss":"' + $pureAppID + '","iat":' + $curTime + ',"exp":' + $expTime + '}'
$encodedHeader = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($pureHeader)) -replace '\+','-' -replace '/','_' -replace '='
$encodedPayload = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($payloadJson)) -replace '\+','-' -replace '/','_' -replace '='
$toSign = $encodedHeader + '.' + $encodedPayload
if ($IsWindows -eq $false) {
if ($RsaPassword.Length -eq 0)
{
$RsaPassword = Read-Host -Prompt "Please enter a password to be used for the private key" -AsSecureString
}
$DecryptedRsaPassword = ConvertFrom-SecureString $RsaPassword -AsPlainText
set-content -value $tosign -Path ./PureOneHeader.txt -NoNewline
Start-Process -FilePath ./openssl -ArgumentList "dgst -binary -sha256 -sign $($PrivateKeyFileLocation) -passin pass:$($DecryptedRsaPassword) -out ./PureOneSignedHeader.txt ./PureOneHeader.txt"
#file lock often still exists, wait for it to release.
start-sleep 1
$signature = openssl base64 -in ./PureOneSignedHeader.txt
$signature = $signature -replace '\+','-' -replace '/','_' -replace '='
Remove-Item -Path ./PureOneSignedHeader.txt
Remove-Item -Path ./PureOneHeader.txt
}
else {
$toSignEncoded = [System.Text.Encoding]::UTF8.GetBytes($toSign)
$signature = [Convert]::ToBase64String($privateKey.SignData($toSignEncoded,[Security.Cryptography.HashAlgorithmName]::SHA256,[Security.Cryptography.RSASignaturePadding]::Pkcs1)) -replace '\+','-' -replace '/','_' -replace '='
}
$jwt = $toSign + '.' + $signature
return $jwt.Replace(" ", "")
}
}
function New-PureOneConnection {
<#
.SYNOPSIS
Takes in a Pure1 Application ID and certificate to create a 10 hour access token.
.DESCRIPTION
Takes in a Pure1 Application ID and certificate to create a 10 hour access token. Can also take in a private key in lieu of the full cert. Will reject if the private key is not properly formatted.
.INPUTS
Pure1 Application ID, a certificate or a private key.
.OUTPUTS
Does not return anything--it stores the Pure1 REST access token in a global variable called $Global:PureOneConnections. Valid for 10 hours.
.EXAMPLE
PS C:\ New-PureOneConnection -pureAppID pure1:apikey:PZogg67LcjImYTiI
Create a Pure1 REST connection using a passed in certificate and the specified Pure1 App ID. Since no certificate/key is specified uses the default certificate/key if it exists.
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> New-PureOneConnection -RsaPassword $password -PureAppID pure1:apikey:TACAwKsXL7kLa96q
Creates a Pure1 REST connection for use with additional Pure1 cmdlets. Since no key location is specified it uses the default key if it exists.
.EXAMPLE
PS C:\ $cert = New-PureOneCertificate
PS C:\ $cert | New-PureOneConnection -pureAppID pure1:apikey:PZogg67LcjImYTiI
Create a Pure1 REST connection using a passed in certificate and the specified Pure1 App ID
.EXAMPLE
PS C:\ $cert = New-PureOneCertificate
PS C:\ $privateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
PS C:\ $privateKey | New-PureOneConnection -pureAppID pure1:apikey:PZogg67LcjImYTiI
Create a Pure1 REST connection using a passed in private key and the specified Pure1 App ID
.EXAMPLE
PS /home/pureuser> $password = Read-Host -AsSecureString
PS /home/pureuser> New-PureOneConnection -PrivateKeyFileLocation /home/pureuser/PureOnePrivate.pem -RsaPassword $password -PureAppID pure1:apikey:TACAwKsXL7kLa96q
Creates a Pure1 REST connection for use with additional Pure1 cmdlets.
.NOTES
Version: 1.3
Author: Cody Hosterman https://codyhosterman.com
Creation Date: 12/04/2020
Purpose/Change: Fix for PowerShell 5.x
*******Disclaimer:******************************************************
This scripts are offered "as is" with no warranty. While this
scripts is tested and working in my environment, it is recommended that you test
this script in a test lab before using in a production environment. Everyone can
use the scripts/commands provided here without any written permission but I
will not be liable for any damage or loss to the system.
************************************************************************
#>
[CmdletBinding(DefaultParameterSetName='AppID')]
Param(
[Parameter(Position=0,ValueFromPipeline=$True,ParameterSetName='Certificate')]
[System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate,
[Parameter(Position=1,mandatory=$True,ParameterSetName='AppID')]
[Parameter(Position=1,mandatory=$True,ParameterSetName='PrivateKey')]
[Parameter(Position=1,mandatory=$True,ParameterSetName='Certificate')]
[Parameter(Position=1,mandatory=$True,ParameterSetName='Unix')]
[string]$PureAppID,
[Parameter(Position=2,ValueFromPipeline=$True,mandatory=$True,ParameterSetName='PrivateKey')]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(Position=3,ParameterSetName='AppID')]
[Parameter(Position=3,ParameterSetName='PrivateKey')]
[Parameter(Position=3,ParameterSetName='Certificate')]
[Parameter(Position=3,ParameterSetName='Unix')]
[switch]$ReturnOrg,
[Parameter(Position=4,ParameterSetName='Unix')]
[string]$PrivateKeyFileLocation,
[Parameter(Position=5,mandatory=$True,ParameterSetName='Unix')]
[securestring]$RsaPassword,
[Parameter(Position=6,ParameterSetName='JWT')]
[string]$Jwt
)Begin {
$checkForOneCert = $false
}
Process {
if ([string]::IsNullOrEmpty($Jwt))
{
if ($checkForOneCert -eq $false)
{
$checkForOneCert = $True
}
else {
throw "Please only pass in one certificate/key at a time. More than one found in the pipelined input for parameter Certificate/private key."
}
}
}
End {
if ([string]::IsNullOrEmpty($Jwt))
{
if (($isWindows -eq $false) -and ([string]::IsNullOrEmpty($RsaPassword)))
{
$RsaPassword = Read-Host "Please enter in the password for your private key" -AsSecureString
}
if (($isWindows -eq $true) -or ($null -eq $isWindows))
{
if (($null -eq $certificate) -and ($null -eq $PrivateKey))
{
$Certificate = Get-PureOneCertificate -ErrorAction SilentlyContinue
if ($null -eq $certificate)
{
throw "Please pass in a certificate or RSA private key."
}
}
if ($null -eq $certificate)
{
$jwt = New-PureOneJwt -privateKey $privateKey -pureAppID $pureAppID -expiration ((Get-Date).AddSeconds(60)) -ErrorAction Stop
}
else
{
$jwt = New-PureOneJwt -certificate $certificate -pureAppID $pureAppID -expiration ((Get-Date).AddSeconds(60)) -ErrorAction Stop
}
}
else
{
if (($isWindows -eq $false) -and ([string]::IsNullOrEmpty($PrivateKeyFileLocation)))
{
$PrivateKeyFileLocation = Get-PureOneCertificate -ErrorAction SilentlyContinue
if ([string]::IsNullOrEmpty($PrivateKeyFileLocation))
{
throw "No default private key found. Please pass in a private key file location or create a new one with New-PureOneCertificate."
}
}
}
try {
$jwt = New-PureOneJwt -PrivateKeyFileLocation $PrivateKeyFileLocation -RsaPassword $RsaPassword -pureAppID $pureAppID -expiration ((Get-Date).AddSeconds(60)) -ErrorAction Stop
}
catch
{
#throw ($_.errordetails.message |ConvertFrom-Json).error_description
}
}
$apiendpoint = $Global:PureOneRestEndpointURL
$AuthAction = @{
grant_type = "urn:ietf:params:oauth:grant-type:token-exchange"
subject_token = $jwt
subject_token_type = "urn:ietf:params:oauth:token-type:jwt"
}
try {
$pureOnetoken = Invoke-RestMethod -Method Post -Uri $apiendpoint -ContentType "application/x-www-form-urlencoded" -Body $AuthAction -ErrorAction Stop
}
catch {
throw ($_.errordetails.message |ConvertFrom-Json).error_description
}
write-debug $pureOnetoken
$orgInfo = Resolve-JWTtoken -token $pureOnetoken
$jwtInfo = Resolve-JWTtoken -token $jwt
$date = get-date "1/1/1970"
$date = $date.AddSeconds($orgInfo.exp).ToLocalTime()
if (($null -eq $isWindows) -or ($isWindows -eq $true))
{
$newOrg = New-Object -TypeName WindowsPureOneOrganization -ArgumentList $orgInfo.org,$pureOnetoken.access_token,$jwtInfo.iss,$orgInfo.max_role,$date,$certificate -ErrorAction Stop
}
else {
$newOrg = New-Object -TypeName UnixPureOneOrganization -ArgumentList $orgInfo.org,$pureOnetoken.access_token,$jwtInfo.iss,$orgInfo.max_role,$date,$RsaPassword,$PrivateKeyFileLocation -ErrorAction Stop
}
if ($Global:PureOneConnections.Count -eq 0)
{
$Global:PureOneConnections += $newOrg
$Global:PureOneConnections[0].SetDefault($true)
}
else
{
foreach ($connection in $Global:PureOneConnections)
{
if ($connection.PureOneOrgID -eq $newOrg.PureOneOrgID)
{
if ($connection.updateLock -eq $false)
{
throw "The Pure1 Organization with ID $($connection.PureOneOrgID) is already connected."
}
else {
$pureOneUpdate = $True
break
}
}
}
if ($pureOneUpdate -ne $true)
{
$Global:PureOneConnections += $newOrg
}
}
if ($returnOrg -eq $true)
{
return $newOrg
}
}
}
function New-PureOneOperation {
<#
.SYNOPSIS
Allows you to run a Pure1 REST operation that has not yet been built into this module.
.DESCRIPTION
Runs a REST operation to Pure1
.INPUTS
A filter/query, an resource, a REST body, and optionally an access token.
.OUTPUTS
Returns Pure1 REST response.
.EXAMPLE
PS C:\ $cert = New-PureOneCertificate
PS C:\ $cert | New-PureOneConnection -pureAppID pure1:apikey:PZogg67LcjImYTiI
PS C:\ New-PureOneOperation -resourceType volumes -restOperationType GET
Create a Pure1 REST connection and requests all volumes
.EXAMPLE
PS C:\ $cert = New-PureOneCertificate
PS C:\ $cert | New-PureOneConnection -pureAppID pure1:apikey:PZogg67LcjImYTiI
PS C:\ New-PureOneOperation -resourceType arrays -restOperationType GET
Create a Pure1 REST connection and requests all arrays
.NOTES
Version: 1.2
Author: Cody Hosterman https://codyhosterman.com
Creation Date: 09/02/2020
Purpose/Change: Core support
*******Disclaimer:******************************************************
This scripts are offered "as is" with no warranty. While this
scripts is tested and working in my environment, it is recommended that you test
this script in a test lab before using in a production environment. Everyone can
use the scripts/commands provided here without any written permission but I
will not be liable for any damage or loss to the system.
************************************************************************
#>
[CmdletBinding()]
Param(
[Parameter(Position=0,mandatory=$True)]
[string]$ResourceType,
[Parameter(Position=1)]
[string]$QueryFilter,
[Parameter(Position=2)]
[string]$JsonBody,
[Parameter(Position=3,mandatory=$True)]
[ValidateSet('POST','GET','DELETE','PUT')]
[string]$RestOperationType,
[Parameter(Position=4)]
[string]$PureOneToken
)
$pureOneHeader = Set-PureOneHeader -pureOneToken $pureOneToken -ErrorAction Stop
Write-Debug $pureOneHeader.authorization
$apiendpoint = "$($global:PureOneRestUrl)/$($global:pureOneRestVersion)/" + $resourceType + $queryFilter
Write-Debug $apiendpoint
$ErrorActionPreference = "Stop"