21 Commits

Author SHA1 Message Date
739c8cb9b0 stop raising build error on lint warnings for now (#49) 2020-10-02 16:06:22 +02:00
5983c760b5 disable error on lint warnings 2020-10-02 15:52:59 +02:00
045adbf647 Modernize Build Pipeline (#48) 2020-10-02 15:48:58 +02:00
b6e791f709 adds security section (#47)
- add security section
- update content
- fix github deployment state
- update about page based on readme.md
2020-01-23 13:06:16 +01:00
d0a6457d37 Adds Social Logo (#46)
* add social logo
* add social logo in Readme
2019-05-10 10:12:26 +02:00
fdc6651588 Publish version 1.0.x (#45)
## About

## Content (Micro Commits)

* fixes #38 
* fixes #44 
* Implement precise lookup hierarchy (fixes #43)
* align pester test with #43 logic
* split cert functions
* use new cert functions for save an lookup
* fix pester tests
* [wip]
* fix var name ref
* fix exports
* fix cert store location for windows shared mode
* fix mandatory params
* fix accidentially removed code block
* add basic cert pester pests
* remove old docs
* update cbh blocks
* update cbh blocks
* update docs
* move .net wrapper forpfx files
* do not export .net wrapper functions
* update docs
* rename tests
* fix private functions location
* - fixes #44: FTP connection
* add link to reference
* add format files
* add preview version shield
* update markdown help files (platyps)
* add emoji images in captions
* fix typos
* fix typos
* fix typo
* prepare version numbers
2019-04-29 16:05:43 +02:00
d92d963979 Publish preview version (#42)
* adds certificate store location

* add additional certificate store tests

* add cert store tests for New-CredentialStoreItem

* fix test

* add error handling for credential store path

* add Import-CSCertificate helper function

* Import new certificate if param is given

* fix extension filter

* add linux error message

* fix pester test for linux

* update cert helper functions

* export helper functions

* fix cs cert import

* simplify cs cret lookup

* remove obsolete functions

* fix pester test for linux

* fix error type for linux

* fix var name

* fix pester test

* disable travis artifact upload

* update cert lookup for item functions

* debug build error

* use cert instance constructor for linux

* disable debug output

* remove obsolete exports
2019-04-04 17:02:17 +02:00
5a68527061 fix Connect-To bug (#41)
* replace internal coverage tools with PSCoverage (#39)

* use PSCoverage instead of internal module

* remove internal pscoverage ref

* remove deprecated and internal coverage module

* fix dependency test for conection types without deps

* - tests should return true for missing deps (fixes #40)

* remove pre release counter

* change prerelease tag
2019-03-15 12:49:43 +01:00
dbf53b7cb0 publish 0.5.xxx-alpha1 release 2019-01-16 13:18:27 +01:00
09548fca0a add debug output (#36) 2019-01-16 13:02:51 +01:00
afab3c870c PowerShell 6 Core Support (#35)
## About
This pull request reflects all changes done in the `linuxsupport` branch.

## Content
- Enable PowerShell 6 Core support
- Use PFX Certificate for encryption ( fixes #32 )
- Updates CI / CD pipeline ( fixes #31 )
- uses portable libressl ( fixes #34 )
- adds `-PassThru` switch for returning current `VIServer` session in `Connect-To` ( fixes #34 )
- adds git lfs for embedded libressl files
- restructured internal functions into `Private` dir
- added certificate related functions
- adds travis build pipeline for tests
2019-01-16 12:55:29 +01:00
ab13962f6e Fix FTP Connection Error (#29)
* fixes #27
* fix var name typo
* bump version
2018-03-26 13:01:34 +02:00
680f37c00e fixed another var name typo 2018-03-21 15:30:14 +01:00
1773f1fc06 fixes #26 2018-03-21 15:18:18 +01:00
c0b13052b3 Enables pipeline input for -Credential parameter (#25) 2018-03-21 14:32:32 +01:00
8d55f2d6fd disable AppVeyor builds for specific branches (fixes #23) 2018-03-21 12:52:59 +01:00
ce823d4564 Increase code coverage (#22) 2018-03-21 12:16:09 +01:00
2422afbd8f Publish version 0.2.1.X (#18)
- fix pester test execution order in vscode test task.
- fix coveralls.io link in bagde.
- skip coverage report creation for PR triggered builds
- update docs
- Connection type SCP added for `Connect-To` and `Disconnect-From`.

## Internal Changes
- pester tests now don't need to dotsource other public functions from the same module (fixes #17 )
  - helper and private functions stilll needs to be dotsourced.
- basic module tests added
- pester tests for `Resolve-Dependency` added
- Wrapper function  `Get-ModuleBase` added. This enables mocking in tests.
2018-03-09 14:02:51 +01:00
691255957c Remove old Write-Message2 function (#13) 2018-03-02 13:43:06 +01:00
cb11209702 Publish 0.2.0 (#12) 2017-12-22 08:10:37 +01:00
6659c2b317 update badges (#11) 2017-11-15 10:17:23 +01:00
109 changed files with 4669 additions and 1551 deletions

32
.drone.yml Normal file
View File

@ -0,0 +1,32 @@
---
kind: pipeline
type: docker
name: Linux_PWSH7_Build
platform:
os: linux
arch: amd64
steps:
- name: Environments
image: mcr.microsoft.com/powershell:latest
commands:
- pwsh -NonInteractive -c "& {Import-Module './tools/DroneIO.psm1' -Verbose; Invoke-ShowEnv -Verbose}"
- pwsh -NonInteractive -c "& {Import-Module './tools/DroneIO.psm1' -Verbose; Invoke-InstallDependencies -Verbose}"
- name: LintTests
image: mcr.microsoft.com/powershell:latest
commands:
- pwsh -NonInteractive -c "& {Import-Module './tools/DroneIO.psm1'; Invoke-InstallDependencies}"
- pwsh -NonInteractive -c "& {Import-Module './tools/DroneIO.psm1'; Invoke-Linter}"
- name: UnitTests
image: mcr.microsoft.com/powershell:latest
commands:
- pwsh -NonInteractive -c "& {Import-Module './tools/DroneIO.psm1'; Invoke-InstallDependencies}"
- pwsh -NonInteractive -c "& {Import-Module './tools/DroneIO.psm1'; Invoke-UnitTests}"
- name: coverage
image: plugins/codecov
settings:
token:
from_secret: CodeCovToken
files:
- coverage.xml

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
src/Vendor/libressl255/* filter=lfs diff=lfs merge=lfs -text
*.pfx filter=lfs diff=lfs merge=lfs -text

96
.vscode/launch.json vendored
View File

@ -1,48 +1,48 @@
{ {
// Use IntelliSense to learn about possible attributes. // Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes. // Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Launch Current File", "name": "PowerShell Launch Current File",
"script": "${file}", "script": "${file}",
"args": [], "args": [],
"cwd": "${file}" "cwd": "${file}"
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Launch Current File in Temporary Console", "name": "PowerShell Launch Current File in Temporary Console",
"script": "${file}", "script": "${file}",
"args": [], "args": [],
"cwd": "${file}", "cwd": "${file}",
"createTemporaryIntegratedConsole": true "createTemporaryIntegratedConsole": true
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Launch Current File w/Args Prompt", "name": "PowerShell Launch Current File w/Args Prompt",
"script": "${file}", "script": "${file}",
"args": [ "args": [
"${command:SpecifyScriptArgs}" "${command:SpecifyScriptArgs}"
], ],
"cwd": "${file}" "cwd": "${file}"
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "attach", "request": "attach",
"name": "PowerShell Attach to Host Process", "name": "PowerShell Attach to Host Process",
"processId": "${command:PickPSHostProcess}", "processId": "${command:PickPSHostProcess}",
"runspaceId": 1 "runspaceId": 1
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Interactive Session", "name": "PowerShell Interactive Session",
"cwd": "${workspaceRoot}" "cwd": ""
} }
] ]
} }

View File

@ -26,7 +26,8 @@
"powershell.codeFormatting.whitespaceAroundOperator": true, "powershell.codeFormatting.whitespaceAroundOperator": true,
"powershell.codeFormatting.whitespaceAfterSeparator": true, "powershell.codeFormatting.whitespaceAfterSeparator": true,
"powershell.codeFormatting.ignoreOneLineBlock": true, "powershell.codeFormatting.ignoreOneLineBlock": true,
"powershell.codeFormatting.alignPropertyValuePairs": false, "powershell.codeFormatting.alignPropertyValuePairs": true,
"powershell.codeFormatting.preset": "Custom",
// cspell spellchecker options // cspell spellchecker options
"cSpell.enabledLanguageIds": [ "cSpell.enabledLanguageIds": [
"c", "c",

2
.vscode/tasks.json vendored
View File

@ -28,7 +28,7 @@
"taskName": "Test", "taskName": "Test",
"suppressTaskName": true, "suppressTaskName": true,
"args": [ "args": [
"Write-Host 'Invoking Pester...'; $ProgressPreference = 'SilentlyContinue'; Invoke-Pester -Script '.\\tests\\*' -EnableExit $flase -PesterOption @{IncludeVSCodeMarker=$true};", "Write-Host 'Invoking Pester...'; $ProgressPreference = 'SilentlyContinue'; Invoke-Pester -Script ( Get-ChildItem -Path '.\\tests\\*.Tests.ps1' -Recurse | Sort-Object -Property Name ) -EnableExit $flase -PesterOption @{IncludeVSCodeMarker=$true};",
"Invoke-Command { Write-Host 'Completed Test task in task runner.' }" "Invoke-Command { Write-Host 'Completed Test task in task runner.' }"
], ],
"problemMatcher": "$pester", "problemMatcher": "$pester",

111
README.md
View File

@ -1,33 +1,85 @@
| AppVeyor Overall | AppVeyor Master | AppVeyor Dev | Coveralls.io | Download | [![AppVeyor branch](https://img.shields.io/appveyor/ci/OCram85/PSCredentialStore/master.svg?style=plastic "Master Branch Build Status")](https://ci.appveyor.com/project/OCram85/pscredentialstore/branch/master)
| :--------------: | :-------------: | :----------: | :-----------: | :--------:| [![AppVeyor tests branch](https://img.shields.io/appveyor/tests/OCram85/PSCredentialStore/master.svg?style=plastic "Pester Tests Results")](https://ci.appveyor.com/project/OCram85/pscredentialstore/branch/master/tests)
| [![Build status](https://ci.appveyor.com/api/projects/status/b4t8x88xai3ee7gk?svg=true)](https://ci.appveyor.com/project/OCram85/PSCredentialStore) | [![Build status](https://ci.appveyor.com/api/projects/status/b4t8x88xai3ee7gk/branch/master?svg=true)](https://ci.appveyor.com/project/OCram85/PSCredentialStore/branch/master) | [![Build status](https://ci.appveyor.com/api/projects/status/b4t8x88xai3ee7gk/branch/dev?svg=true)](https://ci.appveyor.com/project/OCram85/PSCredentialStore/branch/dev) | [![Coverage Status](https://coveralls.io/repos/github/OCram85/PSCredentialStore/badge.svg?branch=master)](https://coveralls.io/github/OCram85/PSCredentialStore?branch=master) | [![Download](https://img.shields.io/badge/powershellgallery-PSCredentialStore-blue.svg)](https://www.powershellgallery.com/packages/PSCredentialStore) [![Coveralls github](https://img.shields.io/coveralls/github/OCram85/PSCredentialStore.svg?style=plastic "Coveralls.io Coverage Report")](https://coveralls.io/github/OCram85/PSCredentialStore?branch=master)
[![codecov](https://codecov.io/gh/OCram85/PSCredentialStore/branch/master/graph/badge.svg)](https://codecov.io/gh/OCram85/PSCredentialStore)
[![PowerShell Gallery](https://img.shields.io/powershellgallery/v/PSCredentialStore.svg?style=plastic "PowershellGallery Published Version")](https://www.powershellgallery.com/packages/PSCredentialStore)
[![PowerShell Gallery](https://img.shields.io/powershellgallery/vpre/PSCredentialStore.svg?label=latest%20preview&style=plastic "PowershellGallery Latest Preview Version")](https://www.powershellgallery.com/packages/PSCredentialStore)
[![PowerShell Gallery](https://img.shields.io/powershellgallery/dt/PSCredentialStore.svg?style=plastic "PowershellGallery Downloads")](https://www.powershellgallery.com/packages/PSCredentialStore)
General ![forthebadge](http://forthebadge.com/images/badges/built-with-love.svg)
![forthebadge](http://forthebadge.com/images/badges/for-you.svg)
![social-logo](/assets/social-logo.png)
:key: General
======= =======
The PSCredentialStore is a simple credential manager for PSCredentials. It stores PSCredentials in a simple json The PSCredentialStore is a simple credential manager for `PSCredential` objects. It stores PSCredentials in a simple json
file. You can choose between a private and shared credential store. The private one exists in your profile and can file. You can choose between a private and shared credential store. The private one exists in your profile and can
ony accessed by your account on the same machine. The shared store enables you to use different credentials for your ony accessed by your account on the same machine. The shared store enables you to use different credentials for your
scripts without exposing them as plain text. scripts without exposing them as plain text.
**The shared store isn't 100% secure and I don't recommend using it in production!**
PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often
need to store credentials for non interactive usage like in scheduled tasks. need to store credentials for non interactive usage like in scheduled tasks.
For more details read the [about_PSCredentialStore](/src/en-US/about_PSCredential.help.txt) page. Starting with version `1.0.0` PSCredential uses Pfx certificates fo encryption. You can use Pfx certificate files
or certificates stored in the certificate store.
Installation For more details read the [about_PSCredentialStore](/docs/about_PSCredentialStore.md) page on github or via CLI with
`Get-Help about_PSCredentialStore`.
You can find the [reference](/docs/PSCredentialStore.md) in the /docs/ path as well.
:vulcan_salute: Requirements
============ ============
PowerShellGallery.com (Recommended Way) - PowerShell >= `5.1`
- .NET Framework >= `4.6` or .NET Core >= `1.0`
:bomb: About Security
============
>This section explains some security topics and the the design decisions we made to balance the usage and security needs.
To be able to delegate `PSCredentials` objects we can't exclusively rely on the `SecureString` cmdlets. You can't
decrypt and reuse such credentials from a different user account or even machine. This is caused by automatically
generated encryption key which, is used create a `Secure String` based encrypted string.
In order to delegate a password, while still using the underlying security framework, we have to provide a custom
encryption key. This leads to the fact, that everyone who has access to the key could encrypt or decrypt your data.
So we decided to use the public and private keys from valid certificates as part of the custom encryption keys to encrypt your data.
This means clearly: Everyone who has access to the `CredentialStore` needs also access to the certificate file to work with it.
Keep in mind you need to secure the access with your NTFS file permissions to avoid unwanted usage. Another option is
to import the certificate into your certification vaults of you operating system. In this case you can grand the
permission to the certificates itself.
Here is s brief hierarchy description of the certificate location: *(First match wins)*
| CredentialStore Type | Certificate Location |
| -------------------- | ---------------------- |
| Private | `CurrentUser`\\`My` |
| Shared (Windows) | `CurrentUser`\\`My` |
| | `LocalMachine`\\`Root` |
| Shared (Linux) | `LocalMachine`\\`My` |
| | `LocalMachine`\\`Root` |
:hammer_and_wrench: Installation
============
:artificial_satellite: PowerShellGallery.com (Recommended Way)
--------------------------------------- ---------------------------------------
* Make sure you use PowerShell 4.0 or higher with `$PSVersionTable`. * Make sure you use PowerShell 5.1 or higher with `$PSVersionTable`.
* Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore` * Use the builtin PackageManagement and install with: `Import-Module PowerShellGet; Install-Module 'PSCredentialStore' -Repository 'PSGallery'`
* Additionally use the `-AllowPrerelease` switch until we publish the final release!
* Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore` * Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore`
Manual Way :building_construction: Manual Way
---------- ----------
* Take a look at the [Latest Release](https://github.com/OCram85/PSCredentialStore/releases/latest) page. * Take a look at the [Latest Release](https://github.com/OCram85/PSCredentialStore/releases/latest) page.
@ -36,19 +88,27 @@ Manual Way
* Don't forget to change the NTFS permission flag in the context menu. * Don't forget to change the NTFS permission flag in the context menu.
* Start with `Import-Module PSCredentialStore` * Start with `Import-Module PSCredentialStore`
Quick Start :sparkles: Quick Start
----------- -----------
**1.** First we need a blank credential store. You can decide between a *private* or *shared* store. The private **1.** First we need a blank credential store. You can decide between a *private* or *shared* store. The private
Credential Store can only be accessed with your profile on the machine you created it. Credential Store can only be accessed with your profile on the machine you created it.
Starting with version `1.0.0` you can decide the storage type of your fresh created certificate. As default
PSCredentialStore creates a new pfx certificate file beside the credential store itself. Optionally you can provide
the parameter `-UseCertStore`. This imports the new certificate in the user or machine certificate store as well.
```powershell ```powershell
# Private credential store # Private credential store
New-CredentialStore New-CredentialStore
# Shared credential rtore # Private credential store with certificate store usage
New-CredentialStore -UseCertStore
# Shared credential store
New-CredentialStore -Shared New-CredentialStore -Shared
#Shared credential store in custom Location #Shared credential store in custom location
New-CredentialStore -Shared -Path 'C:\CredentialStore.json' New-CredentialStore -Shared -Path 'C:\CredentialStore.json'
``` ```
@ -75,6 +135,12 @@ If you have already installed the underlying framework / modules, you can connec
* Required Modules: [`VMware.VimAutomation.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI) * Required Modules: [`VMware.VimAutomation.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI)
* **CisServer** - Establish a connection to the CisServer Service on vCenter Host. * **CisServer** - Establish a connection to the CisServer Service on vCenter Host.
* Required Modules: [`VMware.VimAutomation.Cis.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI) * Required Modules: [`VMware.VimAutomation.Cis.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI)
* **ExchangeHTTP** - Establish a remote connection with an Exchange endpoint via http.
* Requires PowerShell remoting
* **ExchangeHTTPS** - Establish a remote connection with an Exchange endpoint via https.
* Requires PowerShell remoting
* **SCP** - Establish a SCP connection.
* Required Modules: [`WinSCP`](https://www.powershellgallery.com/packages/WinSCP)
Here are some basic examples: Here are some basic examples:
@ -84,4 +150,17 @@ Connect-To -RemoteHost "ftp.myside.local" -Type FTP
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
Connect-To -RemoteHost "esx01.myside.local" -Type VMware Connect-To -RemoteHost "esx01.myside.local" -Type VMware
Connect-To -RemoteHost "vcr.myside.local" -Type CisServer Connect-To -RemoteHost "vcr.myside.local" -Type CisServer
Connect-To -RemoteHost "exchange1.myside.local" -Type ExchangeHTTP
Connect-To -RemoteHost "exchange1.myside.local" -Type ExchangeHTTPS
Connect-To -RemoteHost "ubuntu.myside.local" -Type SCP
``` ```
:pushpin: Credits
-------
A huge thanks to all the people who helped with their projects and indirect contributions which made this possible!
- This module is inspired by the awesome work of Dave Wyatt ([@dlwyatt](https://github.com/dlwyatt)) with articles like these:
- https://powershell.org/2013/11/24/saving-passwords-and-preventing-other-processes-from-decrypting-them/
- https://powershell.org/2014/02/01/revisited-powershell-and-encryption/
- The awesome people from [LibreSSL](http://www.libressl.org/) which publishes the [portable openssl/libressl binaries](https://github.com/libressl-portable/portable)!

42
_.travis.yml Normal file
View File

@ -0,0 +1,42 @@
language: csharp
dotnet: 2.2.101
mono: none
git:
depth: 1000
os:
- linux
# Disable OSX bulds for now
# - osx
sudo: required
dist: xenial
osx_image: xcode8.1
matrix:
fast_finish: true
#addons:
# artifacts:
# paths: ./dist/PowerShellGet.zip
install:
# Default 2.0.0 Ruby is buggy
# Default bundler version is buggy
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then
rvm install ruby-2.3.3;
rvm --default use 2.3.3;
fi
- bash <(wget -O - https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/install-powershell.sh)
- pushd tools
- chmod +x travis.sh
- popd
script:
- echo "TRAVIS_EVENT_TYPE value $TRAVIS_EVENT_TYPE"
- ./tools/travis.sh

View File

@ -1,27 +1,35 @@
version: 0.1.{build} # pre release version:
version: 1.0.{build}
branches: #cache:
only:
- master #branches:
- dev # only:
- debug # - master
# - dev
# - debug
skip_tags: true skip_tags: true
#image: WMF 5 image: Visual Studio 2019
# Test ne build image:
image: Visual Studio 2017
# Install pester module and init the Appveyor support. # Install pester module and init the Appveyor support.
# Enable RDP connection for debugging
#init:
# - ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
install: install:
- ps: Import-Module .\tools\AppVeyor.psm1 - ps: Import-Module .\tools\AppVeyor.psm1
- ps: Invoke-InstallDependencies -Verbose - ps: Invoke-InstallDependencies
environment: environment:
NuGetToken: NuGetToken:
secure: 835qfZIkC9mE7QhkYfOZVAdR8rZhPvxG8BO4CbeaelRQOhlqmaSr8G1DWRJzZ/bS secure: 835qfZIkC9mE7QhkYfOZVAdR8rZhPvxG8BO4CbeaelRQOhlqmaSr8G1DWRJzZ/bS
CoverallsToken: CoverallsToken:
secure: eTjWqHL48MBr8wp1rSgLrXHdtpfDV/uClacP3svlWJfCvn/zVokpuaMnWM5RoyIY secure: eTjWqHL48MBr8wp1rSgLrXHdtpfDV/uClacP3svlWJfCvn/zVokpuaMnWM5RoyIY
CodeCovToken:
secure: LJOvamWIlVORDE7120KcmWVkHxOFYBSN99linyICXXmXLtYm81K/31YeMGiPlgTm
build: false build: false
@ -32,8 +40,14 @@ build_script:
- ps: Invoke-AppVeyorBuild - ps: Invoke-AppVeyorBuild
test_script: test_script:
- ps: Invoke-AppVeyorTests - ps: |
- ps: Invoke-CoverageReport $CodeCoverage = Invoke-AppVeyorTests
if ($null -ne $Env:CoverallsToken) {
Invoke-CoverageReport -PesterCoverageReport $CodeCoverage
}
else {
Write-Warning "No CoverallsToken found. This build seems to be triggered by a PR. Skipping this step..."
}
deploy: deploy:
#- provider: GitHub #- provider: GitHub
@ -47,11 +61,14 @@ deploy:
- provider: GitHub - provider: GitHub
auth_token: auth_token:
secure: M+bBX5/nKdJB0eViP7xtrLVTwf3vGDUA9N2MMprZp2i+9ZR3CBVcJnSzJWUmalhB secure: M+bBX5/nKdJB0eViP7xtrLVTwf3vGDUA9N2MMprZp2i+9ZR3CBVcJnSzJWUmalhB
artifact: PSCredentialStore.zip # upload all NuGet packages to release assets artifact: PSCredentialStore.zip # upload all NuGet packages to release assets
draft: false draft: false
prerelease: false prerelease: false
on: on:
branch: master # release from master branch only branch: master # build release on master branch changes
after_deploy: after_deploy:
- ps: Invoke-AppVeyorPSGallery -OnBranch 'master' - ps: Invoke-AppVeyorPSGallery -OnBranch 'master'
# Pause build until `lock` on desktop is deleted.
#on_finish:
# - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))

BIN
assets/colorscheme.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
assets/logo256.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

BIN
assets/social-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Connect-To # Connect-To
## SYNOPSIS ## SYNOPSIS
@ -14,14 +7,14 @@ Connects to the given host using the stored CredentialStoreItem.
### Private (Default) ### Private (Default)
``` ```
Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] [-PassThru]
[<CommonParameters>] [<CommonParameters>]
``` ```
### Shared ### Shared
``` ```
Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] [-Shared]
[-Path <String>] [-Shared] [<CommonParameters>] [-Path <String>] [-PassThru] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
@ -29,51 +22,56 @@ Establish a connection to the selected host using a stored CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs
``` ```
### -------------------------- EXAMPLE 2 -------------------------- ### BEISPIEL 2
``` ```
Connect-To -RemoteHost "ftp.myside.local" -Type FTP Connect-To -RemoteHost "ftp.myside.local" -Type FTP
``` ```
### -------------------------- EXAMPLE 3 -------------------------- ### BEISPIEL 3
``` ```
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
``` ```
### -------------------------- EXAMPLE 4 -------------------------- ### BEISPIEL 4
``` ```
Connect-To -RemoteHost "esx01.myside.local" -Type VMware Connect-To -RemoteHost "esx01.myside.local" -Type VMware
``` ```
### -------------------------- EXAMPLE 5 -------------------------- ### BEISPIEL 5
``` ```
Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer
``` ```
### -------------------------- EXAMPLE 6 -------------------------- ### BEISPIEL 6
``` ```
$MyCreds = Get-Credential Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
``` ```
Connect-To -RemoteHost "vcr01.myside.local" -Type VMware -Credentials $MyCreds ### BEISPIEL 7
Get-VM -Name "*vlm*" | Select-Object -Property Name ```
Disconnect-From -RemoteHost "vcr01.myside.local" -Type VMware Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
```
## PARAMETERS ## PARAMETERS
### -RemoteHost ### -Credentials
Specify the host, for which you would like to change the credentials. Use this parameter to bypass the stored credentials.
Without this parameter Connect-To tries to read the
needed credentials from the CredentialStore.
If you provide this parameter you skip this lookup behavior.
So you can use it to enable credentials without preparing any user interaction.
```yaml ```yaml
Type: String Type: PSCredential
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: True Required: False
Position: Named Position: Named
Default value: None Default value: None
Accept pipeline input: False Accept pipeline input: False
@ -88,7 +86,7 @@ same hostname.
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -97,42 +95,17 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Type ### -PassThru
Specify the host type of the target. Returns the value from the underlying connection type function.
Currently implemented targets are:
- CiscoUcs Establish a connection to a Cisco UCS fabric interconnect.
- FTP Establish a connection to a FTP host.
- NetAppFAS Establish a connection to a NetApp Clustered ONTAP filer.
- VMware Establish a connection to a VMware vCenter or ESXi host.
- CisServer Establish a connection to a Vmware CisServer.
```yaml ```yaml
Type: String Type: SwitchParameter
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credentials
Use this parameter to bypass the stored credentials.
Without this parameter Connect-To tries to read the
needed credentials from the CredentialStore.
If you provide this parameter you skip this lookup behavior.
So you can use it to enable credentials without preparing any user interaction.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: None Default value: False
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -143,11 +116,26 @@ Define a custom path to a shared CredentialStore.
```yaml ```yaml
Type: String Type: String
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemoteHost
Specify the host, for which you would like to change the credentials.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -160,32 +148,45 @@ can be decrypted across systems.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Type
Specify the host type of the target.
Currently implemented targets are: Possible connection values are:
CiscoUcs, FTP, NetAppFAS, VMware, CisServer, ExchangeHTTP, ExchangeHTTPS, SCP.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Connect-To.ps1
File Name : Connect-To.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Disconnect-From # Disconnect-From
## SYNOPSIS ## SYNOPSIS
@ -21,45 +14,70 @@ Terminates a session established with Connect-To using a CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
Disconnect-From -RemoteHost "ucs.myside.local" -Type CiscoUcs Disconnect-From -RemoteHost "ucs.myside.local" -Type CiscoUcs
``` ```
### -------------------------- EXAMPLE 2 -------------------------- ### BEISPIEL 2
``` ```
Disconnect-From -RemoteHost "ftp.myside.local" -Type FTP Disconnect-From -RemoteHost "ftp.myside.local" -Type FTP
``` ```
### -------------------------- EXAMPLE 3 -------------------------- ### BEISPIEL 3
``` ```
Disconnect-From -RemoteHost "fas.myside.local" -Type NetAppFAS Disconnect-From -RemoteHost "fas.myside.local" -Type NetAppFAS
``` ```
### -------------------------- EXAMPLE 4 -------------------------- ### BEISPIEL 4
``` ```
Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware
``` ```
### -------------------------- EXAMPLE 5 -------------------------- ### BEISPIEL 5
``` ```
Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware -Force:$True Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware -Force:$True
``` ```
### -------------------------- EXAMPLE 6 -------------------------- ### BEISPIEL 6
``` ```
Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer
``` ```
### BEISPIEL 7
```
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
```
### BEISPIEL 8
```
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
```
## PARAMETERS ## PARAMETERS
### -Force
Force the disconnect, even if the disconnect would fail.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemoteHost ### -RemoteHost
Specify the remote endpoint, whose session you would like to terminate. Specify the remote endpoint, whose session you would like to terminate.
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: True Required: True
Position: 1 Position: 1
@ -70,17 +88,13 @@ Accept wildcard characters: False
### -Type ### -Type
Specify the host type of the target. Specify the host type of the target.
Currently implemented targets are: Currently implemented targets are: CiscoUcs, FTP, NetAppFAS, VMware,
- CiscoUcs Terminates the connection from a Cisco UCS Fabric Interconnect. CisServer, ExchangeHTTP, ExchangeHTTPS, SCP.
- FTP Terminates the connection from a FTP host.
- NetAppFAS Terminates the connection from a NetApp Clustered ONTAP filer.
- VMware Terminates the connection from a VMware vCenter or ESXi host.
- CisServer Terminates the connection from a Vmware CisServer.
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: True Required: True
Position: 2 Position: 2
@ -89,38 +103,19 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Force
Force the disconnect, even if the disconnect would fail.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Disconnect-From.ps1
File Name : Disconnect-From.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

71
docs/Get-CSCertificate.md Normal file
View File

@ -0,0 +1,71 @@
# Get-CSCertificate
## SYNOPSIS
Returns the current used valid PfX certificate.
## SYNTAX
```
Get-CSCertificate [-Type] <String> [-Thumbprint] <String> [<CommonParameters>]
```
## DESCRIPTION
Use this function to get the available pfx certificate respecting the config hierarchy.
## EXAMPLES
### BEISPIEL 1
```
Get-CSCertificate -Type 'Shared' -Thumbprint '12334456'
```
## PARAMETERS
### -Thumbprint
Provide the credentials thumbprint for the search.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Type
Select the current credential store type.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [System.Security.Cryptography.X509Certificates.X509Certificate2]
## NOTES
- File Name : Get-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Get-CredentialStore # Get-CredentialStore
## SYNOPSIS ## SYNOPSIS
@ -31,7 +24,7 @@ Get-CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
$CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json" $CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json"
``` ```
@ -44,11 +37,11 @@ Define a custom path to a shared CredentialStore.
```yaml ```yaml
Type: String Type: String
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -61,9 +54,9 @@ can be decrypted across systems.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -71,22 +64,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [PSObject] Returns the credential store content as PSObject. ### [PSObject] Returns the credential store content as PSObject.
## NOTES ## NOTES
\`\`\` - File Name : Get-CredentialStore.ps1
File Name : Get-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Get-CredentialStoreItem # Get-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -19,7 +12,7 @@ Get-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonPara
### Shared ### Shared
``` ```
Get-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared] Get-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Shared] [-Path <String>]
[<CommonParameters>] [<CommonParameters>]
``` ```
@ -28,43 +21,13 @@ Return the credential as PSCredential object.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
$myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" $myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
``` ```
## PARAMETERS ## PARAMETERS
### -Path
Define a custom path to a shared CredentialStore.
```yaml
Type: String
Parameter Sets: Shared
Aliases:
Required: False
Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemoteHost
Specify the host, for which you would like to change the credentials.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Identifier ### -Identifier
Provide a custom identifier to the given remote host key. Provide a custom identifier to the given remote host key.
This enables you to store multiple credentials This enables you to store multiple credentials
@ -74,7 +37,7 @@ For example ad/sys1, ftp/sys1, mssql/sys1
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -83,6 +46,36 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Path
Define a custom path to a shared CredentialStore.
```yaml
Type: String
Parameter Sets: Shared
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemoteHost
Specify the host, for which you would like to change the credentials.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared ### -Shared
Switch to shared mode with this param. Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which This enforces the command to work with a shared CredentialStore which
@ -91,9 +84,9 @@ can be decrypted across systems.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -101,22 +94,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [System.Management.Automation.PSCredential] ### [System.Management.Automation.PSCredential]
## NOTES ## NOTES
\`\`\` - File Name : Get-CredentialStoreItem.ps1
File Name : Get-CredentialStoreItem.ps1 - Author : Messing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -0,0 +1,72 @@
# Import-CSCertificate
## SYNOPSIS
Imports a linked certificate to the valid store location.
## SYNTAX
```
Import-CSCertificate [-Type] <String> [-Path] <FileInfo> [<CommonParameters>]
```
## DESCRIPTION
Import-CSCertificate takes a pfx certificate file and imports it to the supposed certificate store for
private and shared credential stores.
## EXAMPLES
### BEISPIEL 1
```
Import-CSCertificate -Type 'Private' -Path (Join-Path -Path $Env:APPDATA -ChildItem 'PfxCertificate.pfx')
```
## PARAMETERS
### -Path
Provide a valid path to pfx certificate file.
```yaml
Type: FileInfo
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Type
Select between the a private and shared credential store.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [None]
## NOTES
- File Name : Import-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

147
docs/New-CSCertAttribute.md Normal file
View File

@ -0,0 +1,147 @@
# New-CSCertAttribute
## SYNOPSIS
Creates required data for a certificate signing request.
## SYNTAX
```
New-CSCertAttribute [-Country] <String> [-State] <String> [-City] <String> [-Organization] <String>
[-OrganizationalUnitName] <String> [-CommonName] <String> [[-Days] <Int32>] [<CommonParameters>]
```
## DESCRIPTION
Defines the certificate related properties for an upcoming New-PfxCertificate execution.
## EXAMPLES
### BEISPIEL 1
```
New-CSCertAttribute -Country 'DE' -State 'BW' -City 'Karlsruhe' -Organization 'AwesomeIT' -OrganizationalUnitName '' -CommonName 'MyPrivateCert'
```
## PARAMETERS
### -City
Certificate city value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CommonName
The certificate common name.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 6
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Country
County code like EN, DE, IT, FR...
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Days
The validation time itself.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: 7
Default value: 365
Accept pipeline input: False
Accept wildcard characters: False
```
### -Organization
Certificate organization value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -OrganizationalUnitName
Certificate OrganizationalUnitName value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 5
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -State
Certificate state value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [PSCredentialStore.Certificate.CSRDetails]
## NOTES
- File Name : New-CSCertAttribute.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

120
docs/New-CSCertificate.md Normal file
View File

@ -0,0 +1,120 @@
# New-CSCertificate
## SYNOPSIS
Creates a new PFX certificate for the CredentialStore encryption.
## SYNTAX
```
New-CSCertificate [-CRTAttribute] <Object> [[-KeyName] <String>] [[-CertName] <String>] [-WhatIf] [-Confirm]
[<CommonParameters>]
```
## DESCRIPTION
Use this function to create a custom self signed certificate used by the PSCredentialStore module.
## EXAMPLES
### BEISPIEL 1
```
New-CSCertificate -CRTAttribute $CRTAttribute -KeyName './myprivate.key' -CertName './mycert.pfx'
```
## PARAMETERS
### -CertName
Provide a custom full path and name for the PFX certificate file.
The file extension has to be \`*.pfx\`
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: ./certificate.pfx
Accept pipeline input: False
Accept wildcard characters: False
```
### -CRTAttribute
Provide certificate related attributes provided by function New-CRTAttribute.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -KeyName
Provide a custom full path and name for the private key.
The file extension has to be \`*.key\`.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: ./private.key
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before running the cmdlet.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [PSCredentialStore.Certificate.Attribute]
## OUTPUTS
### [None]
## NOTES
- File Name : New-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1,80 +1,98 @@
--- # New-CredentialStore
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Get-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
Returns the Credential from a given remote host item. Creates a new credential store File
## SYNTAX ## SYNTAX
### Private (Default) ### Private (Default)
``` ```
Get-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonParameters>] New-CredentialStore [-Force] [-PassThru] [-SkipPFXCertCreation] [-UseCertStore] [-WhatIf] [-Confirm]
[<CommonParameters>]
``` ```
### Shared ### Shared
``` ```
Get-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared] New-CredentialStore [-Shared] [-Path <FileInfo>] [-Force] [-PassThru] [-SkipPFXCertCreation] [-UseCertStore]
[<CommonParameters>] [-WhatIf] [-Confirm] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
Return the credential as PSCredential object. You need to run this script first to create a new credential store before you try to
save new credentials with New-CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
$myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" New-CredentialStore
``` ```
# Creates a new private CredentialStore
### BEISPIEL 2
```
New-CredentialStore -Force
```
# Resets an existing private CredentialStore
### BEISPIEL 3
```
New-CredentialStore -Shared
```
# Creates a new shared CredentialStore
### BEISPIEL 4
```
New-CredentialStore -Shared -Path "C:\TMP\CredentialStore.json"
```
# Creates a new shared CredentialStore in the given location.
## PARAMETERS ## PARAMETERS
### -Path ### -Force
Define a custom path to a shared CredentialStore. Use this switch to reset an existing store.
The complete content will be wiped.
```yaml ```yaml
Type: String Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: False
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -RemoteHost ### -PassThru
Specify the host, for which you would like to change the credentials. {{ Fill PassThru Description }}
```yaml ```yaml
Type: String Type: SwitchParameter
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: True Required: False
Position: Named Position: Named
Default value: None Default value: False
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Identifier ### -Path
Provide a custom identifier to the given remote host key. Define a location for the new shared CredentialStore.
This enables you to store multiple credentials The default store will be created in
for a single remote host entry. $Env:ProgramData\PSCredentialStore dir.
For example ad/sys1, ftp/sys1, mssql/sys1
```yaml ```yaml
Type: String Type: FileInfo
Parameter Sets: (All) Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -84,14 +102,32 @@ Accept wildcard characters: False
``` ```
### -Shared ### -Shared
Switch to shared mode with this param. Creates a CredentialStore in the Shared mode.
This enforces the command to work with a shared CredentialStore which This enables you to read the CredentialStore Items on
can be decrypted across systems. different systems or profiles.
In addition you can optionally provide a custom path wit the -Path parameter.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -SkipPFXCertCreation
You can skip the pfx certificate creation process.
This makes sense if you have a previously created cert or want to
import a cert in cross-platform environments.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False Required: False
Position: Named Position: Named
@ -100,23 +136,69 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -UseCertStore
Instead of using a plain pfx file beside your CredentialStore file you can import it into the user or machine
certificate store.
In this case the system itself secures the cert and you don't hat to set custom NTFS
permissions so secure your shared certificate.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before running the cmdlet.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [System.Management.Automation.PSCredential] ### ['PSCredentialStore.Store'] Returns the recently created CredentialStore object if the -PassThru parameter
### was given.
## NOTES ## NOTES
\`\`\` - File Name : New-CredentialStore.ps1
File Name : Get-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# New-CredentialStoreItem # New-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -20,8 +13,8 @@ New-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential
### Shared ### Shared
``` ```
New-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] New-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>] [-Shared]
[-Credential <PSCredential>] [-Shared] [<CommonParameters>] [-Path <String>] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
@ -33,40 +26,25 @@ a VIConnection, NetApp FAS or UCS Fabric Interconnect.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
``` ```
## PARAMETERS ## PARAMETERS
### -Path ### -Credential
Define the store in which you would like to add a new item. You can provide credentials optionally as pre existing pscredential object.
```yaml ```yaml
Type: String Type: PSCredential
Parameter Sets: Shared Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemoteHost
The identifier or rather name for the given credentials.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None Default value: None
Accept pipeline input: False Accept pipeline input: True (ByValue)
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -79,7 +57,7 @@ For example ad/sys1, ftp/sys1, mssql/sys1
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -88,13 +66,13 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Credential ### -Path
You can provide credentials optionally as pre existing pscredential object. Define the store in which you would like to add a new item.
```yaml ```yaml
Type: PSCredential Type: String
Parameter Sets: (All) Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -103,15 +81,32 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -RemoteHost
The identifier or rather name for the given credentials.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared ### -Shared
{{Fill Shared Description}} Define the CredentialStore where you want to add the new item.
Default is always personal but can be
changed to shared, or even shared with custom path.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -119,22 +114,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : New-CredentialStoreItem.ps1
File Name : New-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,14 +1,6 @@
---
Module Name: PSCredentialStore
Module Guid: 6800e192-9df8-4e30-b253-eb2c799bbe84
Download Help Link: {{Please enter FwLink manually}}
Help Version: {{Please enter version of help manually (X.X.X.X) format}}
Locale: en-US
---
# PSCredentialStore Module # PSCredentialStore Module
## Description ## Description
PSCredentialStore enables managing multiple PSCredential objects. [about_PSCredentialStore](about_PSCredentialStore.md)
## PSCredentialStore Cmdlets ## PSCredentialStore Cmdlets
### [Connect-To](Connect-To.md) ### [Connect-To](Connect-To.md)
@ -23,12 +15,24 @@ Reads the complete content of the credential store and returns it as a new objec
### [Get-CredentialStoreItem](Get-CredentialStoreItem.md) ### [Get-CredentialStoreItem](Get-CredentialStoreItem.md)
Returns the Credential from a given remote host item. Returns the Credential from a given remote host item.
### [Get-CredentialStoreItem](Get-CredentialStoreItem.md) ### [Get-CSCertificate](Get-CSCertificate.md)
Returns the Credential from a given remote host item. Returns the current used valid PfX certificate.
### [Import-CSCertificate](Import-CSCertificate.md)
Imports a linked certificate to the valid store location.
### [Import-CSCertificate](Import-CSCertificate.md)
Imports a linked certificate to the valid store location.
### [New-CredentialStoreItem](New-CredentialStoreItem.md) ### [New-CredentialStoreItem](New-CredentialStoreItem.md)
Adds a credential store item containing host, user and password to the given store. Adds a credential store item containing host, user and password to the given store.
### [New-CSCertAttribute](New-CSCertAttribute.md)
Creates required data for a certificate signing request.
### [New-CSCertificate](New-CSCertificate.md)
Creates a new PFX certificate for the CredentialStore encryption.
### [Remove-CredentialStoreItem](Remove-CredentialStoreItem.md) ### [Remove-CredentialStoreItem](Remove-CredentialStoreItem.md)
Remove the given credentials from the credential store. Remove the given credentials from the credential store.
@ -41,3 +45,12 @@ Returns the credential store state.
### [Test-CredentialStoreItem](Test-CredentialStoreItem.md) ### [Test-CredentialStoreItem](Test-CredentialStoreItem.md)
Checks if the given RemoteHost identifier combination exists in the credential store. Checks if the given RemoteHost identifier combination exists in the credential store.
### [Test-CSCertificate](Test-CSCertificate.md)
Tests if the linked certificate is store ein the specified cert stores.
### [Test-CSConnection](Test-CSConnection.md)
Returns the connection state of a given type to the remote host.
### [Use-CSCertificate](Use-CSCertificate.md)
Links an existing PFX Certificate to a CredentialStore.

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Remove-CredentialStoreItem # Remove-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -19,7 +12,7 @@ Remove-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonP
### Shared ### Shared
``` ```
Remove-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared] Remove-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Shared] [-Path <String>]
[<CommonParameters>] [<CommonParameters>]
``` ```
@ -28,26 +21,56 @@ Use this CMDLet to completely remove an credential store item.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Remove-CredentialStoreItem -RemoteHost "esx01.myside.local"
``` ```
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc ### BEISPIEL 2
```
Remove-CredentialStoreItem -Shared -RemoteHost "esx01.myside.local"
```
### BEISPIEL 3
```
Remove-CredentialStoreItem -Shared -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
```
### BEISPIEL 4
```
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local" -Identifier svc
```
## PARAMETERS ## PARAMETERS
### -Identifier
Defaults to "".
Specify a string, which separates two CredentialStoreItems for the
same hostname.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path ### -Path
Define the store in which your given host entry already exists. Define the store in which your given host entry already exists.
```yaml ```yaml
Type: String Type: String
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -58,7 +81,7 @@ Specify the host you for which you would like to change the credentials.
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: True Required: True
Position: Named Position: Named
@ -67,23 +90,6 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Identifier
Defaults to "".
Specify a string, which separates two CredentialStoreItems for the
same hostname.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared ### -Shared
Switch to shared mode with this param. Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which This enforces the command to work with a shared CredentialStore which
@ -92,9 +98,9 @@ can be decrypted across systems.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -102,22 +108,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Remove-CredentialStoreItem.ps1
File Name : Remove-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Set-CredentialStoreItem # Set-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -14,56 +7,45 @@ Changes the credentials for the given remote host in the store.
### Private (Default) ### Private (Default)
``` ```
Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonParameters>] Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>]
[<CommonParameters>]
``` ```
### Shared ### Shared
``` ```
Set-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared] Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>] [-Shared]
[<CommonParameters>] [-Path <String>] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
{{Fill in the Description}} Use this function to update your already stored RemoteHost items.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
``` ```
### BEISPIEL 2
```
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
```
## PARAMETERS ## PARAMETERS
### -Path ### -Credential
Define the store in which your given host entry already exists. Provided the new credentials you want to update inside the RemoteHost item.
```yaml ```yaml
Type: String Type: PSCredential
Parameter Sets: Shared Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemoteHost
Specify the host you for which you would like to change the credentials.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None Default value: None
Accept pipeline input: False Accept pipeline input: True (ByValue)
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -75,7 +57,7 @@ same hostname.
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -84,6 +66,36 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Path
Define the store in which your given host entry already exists.
```yaml
Type: String
Parameter Sets: Shared
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemoteHost
Specify the host you for which you would like to change the credentials.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared ### -Shared
Switch to shared mode with this param. Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which This enforces the command to work with a shared CredentialStore which
@ -92,9 +104,9 @@ can be decrypted across systems.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -102,22 +114,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Set-CredentialStoreItem.ps1
File Name : Set-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -0,0 +1,56 @@
# Test-CSCertificate
## SYNOPSIS
Tests if the linked certificate is store ein the specified cert stores.
## SYNTAX
```
Test-CSCertificate [-Type] <String> [<CommonParameters>]
```
## DESCRIPTION
Test-CSCertificate should be an easy high level test for the linked certificate.
## EXAMPLES
### BEISPIEL 1
```
Test-CSCertificate -Type 'Shared'
```
## PARAMETERS
### -Type
Select between 'Private' or 'Shared'.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [bool]
## NOTES
- File Name : Test-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

73
docs/Test-CSConnection.md Normal file
View File

@ -0,0 +1,73 @@
# Test-CSConnection
## SYNOPSIS
Returns the connection state of a given type to the remote host.
## SYNTAX
```
Test-CSConnection [-RemoteHost] <String> [-Type] <String> [<CommonParameters>]
```
## DESCRIPTION
Use this script to check a connection which was established with the \`Connect-To\` cmdlet.
## EXAMPLES
### BEISPIEL 1
```
Test-CMConnection -RemoteHost "vcr01.internal.net" -Type VMware
```
## PARAMETERS
### -RemoteHost
Define the remote host you would like to check.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Type
Define the connection type you would like to check.
See the \`Connect-To\` documentation
for valid type values.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [bool]
## NOTES
- File Name : Test-CSConnection.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Test-CredentialStore # Test-CredentialStore
## SYNOPSIS ## SYNOPSIS
@ -29,13 +22,11 @@ the file exists.
## EXAMPLES ## EXAMPLES
### Example 1 ### BEISPIEL 1
``` ```
PS C:\> {{ Add example code here }} Test-CredentialStore -eq $true
``` ```
{{ Add example description here }}
## PARAMETERS ## PARAMETERS
### -Path ### -Path
@ -44,11 +35,11 @@ Define a custom path to a shared CredentialStore.
```yaml ```yaml
Type: String Type: String
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -61,9 +52,9 @@ can be decrypted across systems.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -71,18 +62,16 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
## OUTPUTS ## OUTPUTS
## NOTES ## NOTES
\`\`\` - File Name : Test-CredentialStore.ps1
File Name : Test-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Test-CredentialStoreItem # Test-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -30,7 +23,7 @@ you try to interact with it.
## EXAMPLES ## EXAMPLES
### -------------------------- EXAMPLE 1 -------------------------- ### BEISPIEL 1
``` ```
If (Test-CredentialStoreItem -RemoteHost "Default") { If (Test-CredentialStoreItem -RemoteHost "Default") {
``` ```
@ -43,6 +36,23 @@ Else {
## PARAMETERS ## PARAMETERS
### -Identifier
Adds an optional identifier to the given RemoteHost.
Makes it possible to store multiple credentials
for a single host.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path ### -Path
Define a custom credential store you try to read from. Define a custom credential store you try to read from.
Without the \`-Path\` parameter Without the \`-Path\` parameter
@ -51,7 +61,7 @@ Without the \`-Path\` parameter
```yaml ```yaml
Type: String Type: String
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -66,7 +76,7 @@ Specify the host, for which you would like to change the credentials.
```yaml ```yaml
Type: String Type: String
Parameter Sets: (All) Parameter Sets: (All)
Aliases: Aliases:
Required: True Required: True
Position: Named Position: Named
@ -75,23 +85,6 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -Identifier
Adds an optional identifier to the given RemoteHost.
Makes it possible to store multiple credentials
for a single host.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared ### -Shared
Switch to shared mode with this param. Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which This enforces the command to work with a shared CredentialStore which
@ -100,7 +93,7 @@ can be decrypted across systems.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
@ -110,22 +103,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Test-CredentialStoreItem.ps1
File Name : Test-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

107
docs/Use-CSCertificate.md Normal file
View File

@ -0,0 +1,107 @@
# Use-CSCertificate
## SYNOPSIS
Links an existing PFX Certificate to a CredentialStore.
## SYNTAX
### Private (Default)
```
Use-CSCertificate -Path <String> [-UseCertStore] [<CommonParameters>]
```
### Shared
```
Use-CSCertificate -Path <String> [-CredentialStore <String>] [-Shared] [-UseCertStore] [<CommonParameters>]
```
## DESCRIPTION
Linking a certificate is needed if you plan to use the same CredentialStore in cross platform scenarios.
## EXAMPLES
### BEISPIEL 1
```
Use-CSCertificate -Path 'C:\cert.pfx'
```
## PARAMETERS
### -CredentialStore
Specify a custom path for a shared credential store.
```yaml
Type: String
Parameter Sets: Shared
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path
Specify the path to the PFX Certificate you want to link for usage.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared
Use the credential store in shared mode.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -UseCertStore
Use the given certificate and import it into the corresponding certificate store.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [None]
## NOTES
File Name : Use-CSCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1 +0,0 @@
theme: jekyll-theme-midnight

View File

@ -1,4 +1,4 @@
# PSCredentialStore # PSCredentialStore
## about_PSCredentialStore ## about_PSCredentialStore
@ -7,24 +7,60 @@ PSCredentialStore enables managing multiple PSCredential objects.
# LONG DESCRIPTION # LONG DESCRIPTION
The PSCredentialStore is an simple credential manager for PSCredentials. It stores multiple credential objects in a The PSCredentialStore is a simple credential manager for `PSCredential` objects. It stores PSCredentials in a simple json
simple json file. You can choose between a private and shared store. The private one exists in your profile and can file. You can choose between a private and shared credential store. The private one exists in your profile and can
ony accessed by your account on the same machine. The shared store enables you to use different credentials for your ony accessed by your account on the same machine. The shared store enables you to use different credentials for your
script without exposing them as plain text. scripts without exposing them as plain text.
**The shared store isn't 100% secure and I don't recommend using it in production!**
PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often
need to store credentials for non interactive usage like in scheduled tasks. need to store credentials for non interactive usage like in scheduled tasks.
To get started read the [about_PSCredentialStore](/src/en-US/about_PSCredential.help.txt) page. Starting with version `1.0.0` PSCredential uses Pfx certificates fo encryption. You can use Pfx certificate files
or certificates stored in the certificate store.
For more details read the [about_PSCredentialStore](/docs/about_PSCredentialStore.md) page on github or via CLI with
`Get-Help about_PSCredentialStore`.
## Requirements
- PowerShell >= `5.1`
- .NET Framework >= `4.6` or .NET Core >= `1.0`
## About Security
>This section explains some security topics and the the design decisions we made to balance the usage and security needs.
To be able to delegate `PSCredentials` objects we can't exclusively rely on the `SecureString` cmdlets. You can't
decrypt and reuse such credentials from a different user account or even machine. This is caused by automatically
generated encryption key which, is used create a `Secure String` based encrypted string.
In order to delegate a password, while still using the underlying security framework, we have to provide a custom
encryption key. This leads to the fact, that everyone who has access to the key could encrypt or decrypt your data.
So we decided to use the public and private keys from valid certificates as part of the custom encryption keys to encrypt your data.
This means clearly: Everyone who has access to the `CredentialStore` needs also access to the certificate file to work with it.
Keep in mind you need to secure the access with your NTFS file permissions to avoid unwanted usage. Another option is
to import the certificate into your certification vaults of you operating system. In this case you can grand the
permission to the certificates itself.
Here is s brief hierarchy description of the certificate location: *(First match wins)*
| CredentialStore Type | Certificate Location |
| -------------------- | ---------------------- |
| Private | `CurrentUser`\\`My` |
| Shared (Windows) | `CurrentUser`\\`My` |
| | `LocalMachine`\\`Root` |
| Shared (Linux) | `LocalMachine`\\`My` |
| | `LocalMachine`\\`Root` |
## Installation ## Installation
## PowerShellGallery.com (Recommended Way) ## PowerShellGallery.com (Recommended Way)
* Make sure you use PowerShell 4.0 or higher with `$PSVersionTable`. * Make sure you use PowerShell 5.1 or higher with `$PSVersionTable`.
* Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore` * Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore`
* Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore` * Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore`
@ -36,19 +72,28 @@ To get started read the [about_PSCredentialStore](/src/en-US/about_PSCredential.
* Don't forget to change the NTFS permission flag in the context menu. * Don't forget to change the NTFS permission flag in the context menu.
* Start with `Import-Module PSCredentialStore` * Start with `Import-Module PSCredentialStore`
**1.** First we need a blank CredentialStore. You can decide between a *private* or *shared* store. The private **1.** First we need a blank credential store. You can decide between a *private* or *shared* store. The private
Credential Store can only be accessed with your profile on the machine you created it. Credential Store can only be accessed with your profile on the machine you created it.
Starting with version `1.0.0` you can decide the storage type of your fresh created certificate. As default
PSCredentialStore creates a new pfx certificate file beside the credential store itself. Optionally you can provide
the parameter `-UseCertStore`. This imports the new certificate in the user or machine certificate store as well.
```powershell ```powershell
# Private Credential Store # Private credential store
New-CredentialStore New-CredentialStore
# Shared Credential Store # Private credential store with certificate store usage
New-CredentialStore -UseCertStore
# Shared credential store
New-CredentialStore -Shared New-CredentialStore -Shared
#Shared CredentialStore in custom Location #Shared credential store in custom Location
New-CredentialStore -Shared -Path 'C:\CredentialStore.json' New-CredentialStore -Shared -Path 'C:\CredentialStore.json'
``` ```
**2.** Now you can manage your CredentialStoreItems: **2.** Now you can manage your CredentialStoreItems:
```powershell ```powershell
# This will prompt for credentials and stores it in a private store # This will prompt for credentials and stores it in a private store
@ -72,7 +117,12 @@ If you have already installed the underlying framework your can connect to:
* Required Modules: [`VMware.VimAutomation.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI) * Required Modules: [`VMware.VimAutomation.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI)
* **CisServer** - Establish a connection to the CisServer Service on vCenter Host. * **CisServer** - Establish a connection to the CisServer Service on vCenter Host.
* Required Modules: [`VMware.VimAutomation.Cis.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI)) * Required Modules: [`VMware.VimAutomation.Cis.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI))
* **ExchangeHTTP** - Establish a remote connection with an Exchange endpoint via http.
* Requires PowerShell remoting
* **ExchangeHTTPS** - Establish a remote connection with an Exchange endpoint via https.
* Requires PowerShell remoting
* **SCP** - Establish a SCP connection.
* Required Modules: [`WinSCP`](https://www.powershellgallery.com/packages/WinSCP)
# EXAMPLES # EXAMPLES
```powershell ```powershell

38
resources/Dependency.json Normal file
View File

@ -0,0 +1,38 @@
{
"Version": 0.1,
"Mandatory": {},
"Optional": [
{
"Name": "foobar2000",
"Modules": [
"foobar2000"
]
},
{
"Name": "foo",
"Modules": [
"foo",
"bar"
]
},
{
"Name": "bar",
"Modules": [
"bar"
]
},
{
"Name": "Existing",
"Modules": [
"PowerShellGet"
]
},
{
"Name": "PSGetMixed",
"Modules": [
"PowerShellGet",
"foobar2000"
]
}
]
}

View File

@ -1,3 +1,3 @@
{ {
"Version": "1.2.0", "Version": "2.0.0",
"Creation": "2016-06-14 08:41:10" "Creation": "2016-06-14 08:41:10"

View File

@ -1 +0,0 @@
!<21><><EFBFBD>p<EFBFBD><07><>H4<48><34><EFBFBD>"=w<><77>S<EFBFBD>2

Binary file not shown.

BIN
resources/cs/PSCredentialStore.pfx (Stored with Git LFS) Normal file

Binary file not shown.

View File

@ -0,0 +1,74 @@
function Get-CSCertificate {
<#
.SYNOPSIS
Returns the current used valid PfX certificate.
.DESCRIPTION
Use this function to get the available pfx certificate respecting the config hierarchy.
.PARAMETER Type
Select the current credential store type.
.PARAMETER Thumbprint
Provide the credentials thumbprint for the search.
.INPUTS
[None]
.OUTPUTS
[System.Security.Cryptography.X509Certificates.X509Certificate2]
.EXAMPLE
Get-CSCertificate -Type 'Shared' -Thumbprint '12334456'
.NOTES
- File Name : Get-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet('Private', 'Shared')]
[string]$Type,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Thumbprint
)
begin {
}
process {
if ($Type -eq 'Private') {
Get-CSPfXCertificate -Thumbprint $Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
}
elseif ($Type -eq 'Shared') {
if ( $isLinux) {
$cert = Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
if ($null -eq $cert) {
Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
else {
Write-Output $cert
}
}
elseif ( (! $isLinux) -or ($isWindows) ) {
$cert = Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'My' -StoreLocation 'LocalMachine'
if ($null -eq $cert) {
Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
else {
Write-Output $cert
}
}
}
}
end {
}
}

View File

@ -0,0 +1,72 @@
function Import-CSCertificate {
<#
.SYNOPSIS
Imports a linked certificate to the valid store location.
.DESCRIPTION
Import-CSCertificate takes a pfx certificate file and imports it to the supposed certificate store for
private and shared credential stores.
.PARAMETER Type
Select between the a private and shared credential store.
.PARAMETER Path
Provide a valid path to pfx certificate file.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
Import-CSCertificate -Type 'Private' -Path (Join-Path -Path $Env:APPDATA -ChildItem 'PfxCertificate.pfx')
.NOTES
- File Name : Import-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet('Private', 'Shared')]
[string]$Type,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.IO.FileInfo]$Path
)
begin {
if (! (Test-Path -Path $Path)) {
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.Exception]::new(
('File {0} not found!') -f $Path
)
}
Write-Error @ErrorParams
}
}
process {
# Import to CurrentUser\My store for windows and linux
if ($Type -eq 'Private') {
Import-CSPfxCertificate -Path $Path -StoreName 'My' -StoreLocation 'CurrentUser' -OpenFlags 'ReadWrite'
}
elseif ( (! $isLinux ) -and ($Type -eq 'Shared') ) {
Import-CSPfxCertificate -Path $Path -StoreName 'My' -StoreLocation 'LocalMachine' -OpenFlags 'ReadWrite'
}
elseif ( ($isLinux) -and ($Type -eq 'Shared') ) {
Import-CSPfxCertificate -Path $Path -StoreName 'My' -StoreLocation 'CurrentUser' -OpenFlags 'ReadWrite'
}
}
end {
}
}

View File

@ -0,0 +1,99 @@
function New-CSCertAttribute {
<#
.SYNOPSIS
Creates required data for a certificate signing request.
.DESCRIPTION
Defines the certificate related properties for an upcoming New-PfxCertificate execution.
.PARAMETER Country
County code like EN, DE, IT, FR...
.PARAMETER State
Certificate state value.
.PARAMETER City
Certificate city value.
.PARAMETER Organization
Certificate organization value.
.PARAMETER OrganizationalUnitName
Certificate OrganizationalUnitName value.
.PARAMETER CommonName
The certificate common name.
.PARAMETER Days
The validation time itself.
.INPUTS
[None]
.OUTPUTS
[PSCredentialStore.Certificate.CSRDetails]
.EXAMPLE
New-CSCertAttribute -Country 'DE' -State 'BW' -City 'Karlsruhe' -Organization 'AwesomeIT' -OrganizationalUnitName '' -CommonName 'MyPrivateCert'
.NOTES
- File Name : New-CSCertAttribute.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType('PSCredentialStore.Certificate.Attribute')]
param(
[Parameter(Mandatory = $true)]
[ValidateLength(2, 2)]
[ValidateNotNull()]
[string]$Country,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$State,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$City,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$Organization,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$OrganizationalUnitName,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$CommonName,
[Parameter(Mandatory = $false)]
[ValidateNotNull()]
[int]$Days = 365
)
begin {
}
process {
return [PSCustomObject]@{
PSTypeName = 'PSCredentialStore.Certificate.Attribute'
Subject = [PSCustomObject]@{
PSTypeName = 'PSCredentialStore.Certificate.Attribute.Subject'
Country = $Country
State = $State
City = $City
Organization = $Organization
OrganizationalUnitName = $OrganizationalUnitName
CommonName = $CommonName
}
Days = $Days
}
}
end {
}
}

View File

@ -0,0 +1,142 @@
function New-CSCertificate {
<#
.SYNOPSIS
Creates a new PFX certificate for the CredentialStore encryption.
.DESCRIPTION
Use this function to create a custom self signed certificate used by the PSCredentialStore module.
.PARAMETER CRTAttribute
Provide certificate related attributes provided by function New-CRTAttribute.
.PARAMETER KeyName
Provide a custom full path and name for the private key. The file extension has to be `*.key`.
.PARAMETER CertName
Provide a custom full path and name for the PFX certificate file. The file extension has to be `*.pfx`
.INPUTS
[PSCredentialStore.Certificate.Attribute]
.OUTPUTS
[None]
.EXAMPLE
New-CSCertificate -CRTAttribute $CRTAttribute -KeyName './myprivate.key' -CertName './mycert.pfx'
.NOTES
- File Name : New-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(SupportsShouldProcess = $true)]
[OutputType()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[PSTypeName('PSCredentialStore.Certificate.Attribute')]$CRTAttribute,
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$KeyName = './private.key',
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$CertName = './certificate.pfx'
)
begin {
$ModuleBase = Get-ModuleBase
if ($isLinux -or $isMacOS) {
try {
$openssl = Get-Command -Name 'openssl' -ErrorAction Stop
}
catch {
$_.Exception.Message | Write-Error
$ErrorParams = @{
Message = 'Can not find the openssl binary!'
ErrorAction = 'Stop'
Exception = [System.IO.FileNotFoundException]::new()
}
Write-Error @ErrorParams
}
}
elseif (($PSVersionTable.PSEdition -eq 'Desktop' -and $PSVersionTable.PSVersion.Major -lt 6) -or ($IsWindows -eq $true)) {
$openssl = Join-Path -Path $ModuleBase -ChildPath '/Vendor/libressl255/openssl.exe'
}
$Env:OPENSSL_CONF = Join-Path $ModuleBase -ChildPath '/openssl.conf'
}
process {
$SubjPattern = "/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}"
$SubjValues = @(
$CRTAttribute.Subject.Country,
$CRTAttribute.Subject.State,
$CRTAttribute.Subject.City,
$CRTAttribute.Subject.Organization,
$CRTAttribute.Subject.OrganizationalUnitName,
$CRTAttribute.Subject.CommonName
)
$Subj = $SubjPattern -f $SubjValues
$PEMCertName = $CertName -replace '.pfx', '.crt'
$ExpPattern = '& ''{0}'' req -x509 -sha256 -nodes -days {1} -newkey rsa:2048 -keyout {2} -out {3} -subj "{4}" *>$null'
$ExpValues = @(
$openssl,
$CRTAttribute.Days
$KeyName,
$PEMCertName,
$Subj
)
$PEMExp = $ExpPattern -f $ExpValues
Write-Verbose -Message ( 'Expr string is: {0}' -f $PEMExp)
# Edit the Error action for the openSLL command to make the redirect *>$null work.
# There is always a stderr and stdout stream!
$EAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
Invoke-Expression -Command $PEMExp
$ErrorActionPreference = $EAP
# manually testing the openssl command results
if (! (Test-Path -Path $KeyName)) {
$ErrorParams = @{
Message = 'Could not create the private key ${0}' -f $KeyName
ErrorAction = 'Stop'
Exception = [System.UnauthorizedAccessException]::new()
}
Write-Error @ErrorParams
}
if (! (Test-Path -Path $PEMCertName)) {
$ErrorParams = @{
Message = 'Could not create the PEM certificate ${0}' -f $PEMCertName
ErrorAction = 'Stop'
Exception = [System.Exception]::new()
}
Write-Error @ErrorParams
}
$PfxPattern = '& ''{0}'' pkcs12 -export -out {1} -inkey {2} -in {3} -passout pass:'
$PfxValues = @(
$openssl,
$CertName,
$KeyName,
($CertName -replace '.pfx', '.crt')
)
$PfxExp = $PfxPattern -f $PfxValues
Write-Verbose -Message ( 'PfxExp string is: {0}' -f $PfxExp)
Invoke-Expression -Command $PfxExp
# Remove private key and crt file. Always ask user
Remove-Item -Path $KeyName
Remove-Item -Path ($CertName -replace '.pfx', '.crt')
}
end {
Remove-Item Env:\OPENSSL_CONF -Confirm:$False -Force -ErrorAction SilentlyContinue
}
}

View File

@ -0,0 +1,76 @@
function Test-CSCertificate {
<#
.SYNOPSIS
Tests if the linked certificate is store ein the specified cert stores.
.DESCRIPTION
Test-CSCertificate should be an easy high level test for the linked certificate.
.PARAMETER Type
Select between 'Private' or 'Shared'.
.INPUTS
[None]
.OUTPUTS
[bool]
.EXAMPLE
Test-CSCertificate -Type 'Shared'
.NOTES
- File Name : Test-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet('Private', 'Shared')]
[string]$Type
)
begin {
if ($Type -eq 'Private') {
$CS = Get-CredentialStore
}
elseif ($Type -eq 'Shared') {
$CS = Get-CredentialStore -Shared
}
if ($null -ne $CS.PfxCertificate) {
Write-Warning 'There is a Pfx certificate file linked in the store. Certificates saved in the Cert store will be ignored!'
}
}
process {
if ($Type -eq 'Private') {
$cert = Get-CSPfXCertificate -Thumbprint $CS.Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
}
elseif ($Type -eq 'Shared') {
if ( $isLinux) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
if ($null -eq $cert) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
}
elseif ( (! $isLinux) -or ($isWindows) ) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'My' -StoreLocation 'LocalMachine'
if ($null -eq $cert) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
}
}
if ($null -eq $cert) {
return $false
}
else {
return $true
}
}
end {
}
}

View File

@ -0,0 +1,121 @@
function Use-CSCertificate {
<#
.SYNOPSIS
Links an existing PFX Certificate to a CredentialStore.
.DESCRIPTION
Linking a certificate is needed if you plan to use the same CredentialStore in cross platform scenarios.
.PARAMETER Path
Specify the path to the PFX Certificate you want to link for usage.
.PARAMETER CredentialStore
Specify a custom path for a shared credential store.
.PARAMETER Shared
Use the credential store in shared mode.
.PARAMETER UseCertStore
Use the given certificate and import it into the corresponding certificate store.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
Use-CSCertificate -Path 'C:\cert.pfx'
.NOTES
File Name : Use-CSCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType()]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
param(
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()]
[string]$CredentialStore,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$UseCertStore
)
begin { }
process {
try {
# We need to resolve the path to make sure it has the correct platform specific syntax.
# And it should also exist.
$validPath = Resolve-Path -Path $Path -ErrorAction Stop
$PfxCertificate = Get-PfxCertificate -FilePath $validPath -ErrorAction Stop
}
catch {
$_.Exception.Error | Write-Error
$ErrorParams = @{
Message = 'The given PFX certificate does not exist!'
ErrorAction = 'Stop'
}
Write-Error @ErrorParams
}
try {
if ($PSCmdlet.ParameterSetName -eq "Private") {
$StorePath = Get-DefaultCredentialStorePath
$CS = Get-CredentialStore
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared" ) {
if (!($PSBoundParameters.ContainsKey('CredentialStore'))) {
$StorePath = Get-DefaultCredentialStorePath -Shared
$CS = Get-CredentialStore -Shared
}
else {
$StorePath = $CredentialStore
$CS = Get-CredentialStore -Shared -Path $CredentialStore
}
}
}
catch {
$_.Exception.Error | Write-Error
$ErrorParams = @{
Message = 'The given CredentialStore does not exist!'
ErrorAction = 'Stop'
}
Write-Error @ErrorParams
}
# Lets first check if the thumbprint matches
if (($CS.Thumbprint -notmatch $PfxCertificate.Thumbprint) -and ($CS.Thumbprint.Length -ne 0)) {
Write-Warning @"
You are trying to map an unknown certificate.
Make sure you used the same AES keys for encrypting!
"@
}
if ($UseCertStore) {
Import-CSCertificate -Type $PSCmdlet.ParameterSetName -Path $Path
$CS.Thumbprint = $PfxCertificate.Thumbprint
$CS.PfxCertificate = $null
}
else {
$CS.PfxCertificate = $validPath.Path
}
$CS | ConvertTo-Json -Depth 5 | Out-File -FilePath $StorePath -Force -Encoding utf8
}
end { }
}

View File

@ -1,45 +0,0 @@
function Get-ChallengeFile {
<#
.SYNOPSIS
Reads the challenge file as binary content.
.DESCRIPTION
Use this function to tread a challenge file. Returns a [Byte[]] Array.
.PARAMETER Path
Specify a file to read.
.INPUTS
[None]
.OUTPUTS
[Byte[]]
.EXAMPLE
.\Get-RandomKey -Path "C:\TMP\Challenge.bin"
.NOTES
```
File Name : Get-ChallengeFile.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
```
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$Path = "{0}\PSCredentialStore\Challenge.bin" -f $env:ProgramData
)
if (Test-Path $Path) {
try {
[io.file]::ReadAllBytes($Path)
}
catch {
Write-Error ("Could not read file {0}." -f $Path) -ErrorAction Stop
}
}
}

View File

@ -1,72 +0,0 @@
Function Set-ChallengeFile() {
<#
.SYNOPSIS
Writes the given key into the challenge file
.DESCRIPTION
You can use the file content for ConvertTo-SecureString operations.
.PARAMETER Path
The file you wish to create.
.PARAMETER KeySize
Specify the key size for the encryption key.
.PARAMETER Force
Use this switch to override an older file version.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
.\Set-ChallengeFile -Path "C:\TMP\myfile.json" -Force
.NOTES
File Name : Set-ChallengeFile.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$Path = "{0}\PSCredentialStore\Challenge.bin" -f $env:ProgramData,
[Parameter(Mandatory = $false)]
[ValidateSet(16, 24, 32)]
[string]$KeySize = "24",
[switch]$Force
)
if ((Test-Path -Path $Path)) {
if ($Force -eq $true) {
Remove-Item -Path $Path -Confirm:$false -Force
}
else {
Write-Error "The given file already exists!. Use the -Force switch to override it." -ErrorAction Stop
}
}
$PSCredentialStoreDataDir = Split-Path -Path $Path -Parent
if (-not (Test-Path $PSCredentialStoreDataDir)) {
try {
New-Item -ItemType Directory -Path $PSCredentialStoreDataDir
}
catch {
Write-Error ("Could not create the parent data dir {0}" -f $PSCredentialDataDir) -ErrorAction Stop
}
}
try {
$Keys = Get-RandomKey -Size $KeySize
[io.file]::WriteAllBytes($Path, $Keys)
}
catch {
$_.Exception | Format-List -Force | Out-String | Write-Error -ErrorAction Stop
}
}

View File

@ -1,48 +0,0 @@
function Test-ChallengeFile {
<#
.SYNOPSIS
Simple path check for challenge file needed by the CredentialStores.
.DESCRIPTION
This is supposed to be a internal function to check the existence for a challenge file.
.PARAMETER Path
Specify the path to the challenge file.
.INPUTS
[None]
.OUTPUTS
[Bool].
.EXAMPLE
If (Test-ChallengeFile) {
Write-Host "The file exists."
}
Else {
Write-Warning "Couldn't find the given file!"
}
.NOTES
File Name : Test-ChallengeFile.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String]$Path = "{0}\PSCredentialStore\Challenge.bin" -f $env:ProgramData
)
if (Test-Path $Path) {
$true
}
else {
$false
}
}

View File

@ -14,12 +14,8 @@ function Connect-To {
same hostname. same hostname.
.PARAMETER Type .PARAMETER Type
Specify the host type of the target. Currently implemented targets are: Specify the host type of the target. Currently implemented targets are: Possible connection values are:
- CiscoUcs Establish a connection to a Cisco UCS fabric interconnect. CiscoUcs, FTP, NetAppFAS, VMware, CisServer, ExchangeHTTP, ExchangeHTTPS, SCP.
- FTP Establish a connection to a FTP host.
- NetAppFAS Establish a connection to a NetApp Clustered ONTAP filer.
- VMware Establish a connection to a VMware vCenter or ESXi host.
- CisServer Establish a connection to a Vmware CisServer.
.PARAMETER Credentials .PARAMETER Credentials
Use this parameter to bypass the stored credentials. Without this parameter Connect-To tries to read the Use this parameter to bypass the stored credentials. Without this parameter Connect-To tries to read the
@ -33,6 +29,9 @@ function Connect-To {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems. can be decrypted across systems.
.PARAMETER PassThru
Returns the value from the underlying connection type function.
.INPUTS .INPUTS
[None] [None]
@ -55,49 +54,72 @@ function Connect-To {
Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer
.EXAMPLE .EXAMPLE
$MyCreds = Get-Credential Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
Connect-To -RemoteHost "vcr01.myside.local" -Type VMware -Credentials $MyCreds
Get-VM -Name "*vlm*" | Select-Object -Property Name .EXAMPLE
Disconnect-From -RemoteHost "vcr01.myside.local" -Type VMware Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
.NOTES .NOTES
``` - File Name : Connect-To.ps1
File Name : Connect-To.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[String]$RemoteHost, [string]$RemoteHost,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = "Private")] [Parameter(Mandatory = $false, ParameterSetName = "Private")]
[String]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[ValidateSet("CiscoUcs", "FTP", "NetAppFAS", "VMware", "CisServer")] [ValidateSet(
[String]$Type, 'CiscoUcs',
'FTP',
'NetAppFAS',
'VMware',
'CisServer',
'ExchangeHTTP',
'ExchangeHTTPS',
'SCP'
)]
[string]$Type,
[Parameter(Mandatory = $False, ParameterSetName = "Shared")] [Parameter(Mandatory = $False, ParameterSetName = "Shared")]
[Parameter(Mandatory = $False, ParameterSetName = "Private")] [Parameter(Mandatory = $False, ParameterSetName = "Private")]
[PSCredential]$Credentials, [PSCredential]$Credentials,
[Parameter(Mandatory = $true, ParameterSetNAme = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $False, ParameterSetName = "Shared")] [Parameter(Mandatory = $False, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[String]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData, [string]$Path,
[Parameter(Mandatory = $false, ParameterSetNAme = "Shared")] [Parameter(Mandatory = $False, ParameterSetName = "Private")]
[Switch]$Shared [Parameter(Mandatory = $False, ParameterSetName = "Shared")]
[switch]$PassThru
) )
begin { begin {
# Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
# First check the optional modules # First check the optional modules
if (-not (Resolve-Dependency -Name $Type)) { if (-not (Resolve-Dependency -Name $Type)) {
Write-Error -Message ("Could not resolve the optional dependencies defined for {0}" -f $Type) -ErrorAction 'Stop' Write-Error -Message ("Could not resolve the optional dependencies defined for {0}" -f $Type) -ErrorAction 'Stop'
@ -114,10 +136,6 @@ function Connect-To {
} }
process { process {
# Set the correct CredentialStore Path depending on the used ParameterSetName
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
if (-not ($Credentials)) { if (-not ($Credentials)) {
# Load the credential from the CredentialStore. If the credential doesn't exist, we need to # Load the credential from the CredentialStore. If the credential doesn't exist, we need to
# return 1, so a calling if statement can handle the failure detection. # return 1, so a calling if statement can handle the failure detection.
@ -127,15 +145,19 @@ function Connect-To {
try { try {
if ($Identifier -ne "") { if ($Identifier -ne "") {
$RemoteHostIdentifier = "{0}/{1}" -f $Identifier, $RemoteHost $RemoteHostIdentifier = "{0}/{1}" -f $Identifier, $RemoteHost
$creds = Get-CredentialStoreItem -RemoteHost $RemoteHostIdentifier -Path $Path $creds = Get-CredentialStoreItem -Shared -RemoteHost $RemoteHostIdentifier -Path $Path
} }
else { else {
$creds = Get-CredentialStoreItem -RemoteHost $RemoteHost -Path $Path $creds = Get-CredentialStoreItem -Shared -RemoteHost $RemoteHost -Path $Path
} }
} }
catch { catch {
Write-Message2 ("Unable to look up credential store item for RemoteHost {0}/Identifier {1}!" -f $RemoteHost, $Identifier) -ErrorAction Stop $MessageParams = @{
Message = "Unable to look up credential store item for RemoteHost {0}/Identifier {1}!" -f $RemoteHost, $Identifier
ErrorAction = "Stop"
}
Write-Error @MessageParams
} }
} }
else { else {
@ -143,8 +165,11 @@ function Connect-To {
} }
if ($creds.UserName -eq "" -or $creds.Password.GetType().Name -ne "SecureString") { if ($creds.UserName -eq "" -or $creds.Password.GetType().Name -ne "SecureString") {
# Write a error message to the log. $MessageParams = @{
Write-Message2 ("Please provide valid credentials for RemoteHost {0}!" -f $RemoteHost) -ErrorAction Stop Message = "Please provide valid credentials for RemoteHost {0}!" -f $RemoteHost
ErrorAction = "Stop"
}
Write-Error @MessageParams
} }
else { else {
switch ($Type) { switch ($Type) {
@ -155,20 +180,24 @@ function Connect-To {
} }
catch { catch {
# Write a error message to the log. $MessageParams = @{
Write-Message2 ("Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type) -ErrorAction Stop Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
} }
} }
"FTP" { "FTP" {
# First establish the FTP session # First establish the FTP session
$WinSCPConParams = @{ $WinSCPConParams = @{
Credential = $creds Credential = $creds
Hostname = $RemoteHost Hostname = $RemoteHost
Protocol = 'Ftp' Protocol = 'Ftp'
FtpMode = 'Passive' FtpMode = 'Passive'
} }
try { try {
$Global:WinSCPSession = New-WinSCPSession @WinSCPConParams $FTPSessionOption = New-WinSCPSessionOption @WinSCPConParams
$Global:WinSCPSession = New-WinSCPSession -SessionOption $FTPSessionOption
} }
catch { catch {
throw "Could not connect to {0} using {1} protocol!" -f $RemoteHost, $Type throw "Could not connect to {0} using {1} protocol!" -f $RemoteHost, $Type
@ -177,7 +206,7 @@ function Connect-To {
if (!($WinSCPSession.Opened)) { if (!($WinSCPSession.Opened)) {
# Check the connection state and find out if the session is still open. # Check the connection state and find out if the session is still open.
$MessageParams = @{ $MessageParams = @{
Message = "Connection to {0} using Type {1} was established. But now it seems to be lost!" -f $RemoteHost, $Type Message = "Connection to {0} using Type {1} was established. But now it seems to be lost!" -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -191,7 +220,7 @@ function Connect-To {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -205,7 +234,7 @@ function Connect-To {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -213,13 +242,87 @@ function Connect-To {
} }
"CisServer" { "CisServer" {
try { try {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop | Out-Null if ($PassThru.IsPresent) {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop
}
else {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop | Out-Null
}
} }
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
"ExchangeHTTP" {
try {
$ConnectionParams = @{
ConnectionURI = "http://{0}/powershell" -f $RemoteHost
ConfigurationName = 'Microsoft.Exchange'
Credential = $creds
ErrorAction = 'Stop'
}
$Global:PSExchangeRemote = New-PSSession @ConnectionParams
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
"ExchangeHTTPS" {
try {
$ConnectionParams = @{
ConnectionURI = "https://{0}/powershell" -f $RemoteHost
ConfigurationName = 'Microsoft.Exchange'
Credential = $creds
ErrorAction = 'Stop'
}
$Global:PSExchangeRemote = New-PSSession @ConnectionParams
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
"SCP" {
$WinSCPSessionParams = @{
Credential = $creds
Hostname = $RemoteHost
Protocol = 'Scp'
GiveUpSecurityAndAcceptAnySshHostKey = $True
}
try {
$SessionOption = New-WinSCPSessionOption @WinSCPSessionParams
$Global:WinSCPSession = New-WinSCPSession -SessionOption $SessionOption
Write-Verbose -Message ("SCP Connection established with {0}" -f $Global:WinSCPSession.Hostname)
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
# Check the Connection State
if (!($WinSCPSession.Opened)) {
# Check the connection state and find out if the session is still open.
$MessageParams = @{
Message = "Connection to {0} using Type {1} was established. But now it seems to be lost!" -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -228,7 +331,7 @@ function Connect-To {
default { default {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams

View File

@ -14,12 +14,9 @@ function Disconnect-From {
same hostname. same hostname.
.PARAMETER Type .PARAMETER Type
Specify the host type of the target. Currently implemented targets are: Specify the host type of the target. Currently implemented targets are: CiscoUcs, FTP, NetAppFAS, VMware,
- CiscoUcs Terminates the connection from a Cisco UCS Fabric Interconnect. CisServer, ExchangeHTTP, ExchangeHTTPS, SCP.
- FTP Terminates the connection from a FTP host.
- NetAppFAS Terminates the connection from a NetApp Clustered ONTAP filer.
- VMware Terminates the connection from a VMware vCenter or ESXi host.
- CisServer Terminates the connection from a Vmware CisServer.
.PARAMETER Force .PARAMETER Force
Force the disconnect, even if the disconnect would fail. Force the disconnect, even if the disconnect would fail.
@ -47,12 +44,16 @@ function Disconnect-From {
.EXAMPLE .EXAMPLE
Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer
.EXAMPLE
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
.EXAMPLE
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
.NOTES .NOTES
``` - File Name : Disconnect-From.ps1
File Name : Disconnect-From.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -64,14 +65,23 @@ function Disconnect-From {
[string]$RemoteHost, [string]$RemoteHost,
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[ValidateSet("CiscoUcs", "FTP", "NetAppFAS", "VMware", "CisServer")] [ValidateSet(
'CiscoUcs',
'FTP',
'NetAppFAS',
'VMware',
'CisServer',
'ExchangeHTTP',
'ExchangeHTTPS',
'SCP'
)]
[string]$Type, [string]$Type,
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[switch]$Force [switch]$Force
) )
switch ($Type) { switch -Regex ($Type) {
"VMware" { "VMware" {
try { try {
if ($Force) { if ($Force) {
@ -85,7 +95,7 @@ function Disconnect-From {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -104,7 +114,7 @@ function Disconnect-From {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -117,7 +127,7 @@ function Disconnect-From {
} }
else { else {
$MessageParams = @{ $MessageParams = @{
Message = "There is no open WinSCP Session" Message = "There is no open WinSCP Session"
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -128,16 +138,17 @@ function Disconnect-From {
"NetAppFAS" { "NetAppFAS" {
try { try {
$MessageParams = @{ $MessageParams = @{
Message = "Setting {0} to `$null, which will disconnect NetAppFAS" -f $Global:CurrentNcController Message = "Setting {0} to `$null, which will disconnect NetAppFAS" -f $Global:CurrentNcController
ErrorAction = "Continue" ErrorAction = "Continue"
} }
Write-Verbose @MessageParams Write-Verbose @MessageParams
$Global:CurrentNcController = $null $Global:CurrentNcController = $null
} }
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -152,7 +163,32 @@ function Disconnect-From {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
"ExchangeHTTP*" {
try {
Get-Variable -Name 'PSExchangeRemote' -Scope Global -ErrorAction Stop
Remove-PSSession -Session $Global:PSExchangeRemote -ErrorAction Stop
}
catch {
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
"SCP" {
if ($Global:WinSCPSession.Opened) {
Remove-WinSCPSession -WinSCPSession $Global:WinSCPSession
}
else {
$MessageParams = @{
Message = "There is no open WinSCP Session"
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -161,7 +197,7 @@ function Disconnect-From {
default { default {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams

View File

@ -0,0 +1,114 @@
function Test-CSConnection {
<#
.SYNOPSIS
Returns the connection state of a given type to the remote host.
.DESCRIPTION
Use this script to check a connection which was established with the `Connect-To` cmdlet.
.PARAMETER RemoteHost
Define the remote host you would like to check.
.Parameter Type
Define the connection type you would like to check. See the `Connect-To` documentation
for valid type values.
.INPUTS
[None]
.OUTPUTS
[bool]
.EXAMPLE
Test-CMConnection -RemoteHost "vcr01.internal.net" -Type VMware
.NOTES
- File Name : Test-CSConnection.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$RemoteHost,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[ValidateSet("CiscoUcs", "FTP", "NetAppFAS", "VMware")]
[string]$Type
)
switch ($Type) {
'VMware' {
try {
$Conn = Get-Variable -Name DefaultVIServer -Scope Global -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
$MsgParams = @{
Message = "There is no open PowerCLI VMware connection bound to 'DefaultVIServer'."
}
Write-Verbose @MsgParams
return $false
}
if ($Conn.Value.Name -eq $RemoteHost) {
if ($Conn.Value.IsConnected) {
$MsgParams = @{
Message = "'DefaultVIServer' found. Connection to given remote host already established."
}
Write-Verbose @MsgParams
return $True
}
else {
$MsgParams = @{
Message = "'DefaultVIServer' found. RemoteHost matches but the connection is closed."
}
Write-Verbose @MsgParams
return $false
}
}
}
'CiscoUcs' {
$MsgParams = @{
ErrorAction = "Stop"
Message = "CiscoUCS connection test is not implemented yet!"
}
Write-Error @MsgParams
return $false
}
'FTP' {
$MsgParams = @{
ErrorAction = "Stop"
Message = "FTP connection test is not implemented yet!"
}
Write-Error @MsgParams
return $false
}
'NetAppFAS' {
$MsgParams = @{
ErrorAction = "Stop"
Message = "NetAppFAS connection test is not implemented yet!"
}
Write-Error @MsgParams
return $false
}
# The Default section will never be shown as long as the powershell framework isn't broken.
Default {
$MsgParams = @{
ErrorAction = "Stop"
Message = "Panic: There is an invalid type value! This error should never be thrown."
}
Write-Error @MsgParams
return $false
}
}
}

View File

@ -32,6 +32,12 @@
"Modules": [ "Modules": [
"VMware.VimAutomation.Cis.Core" "VMware.VimAutomation.Cis.Core"
] ]
},
{
"Name": "SCP",
"Modules": [
"WinSCP"
]
} }
] ]
} }

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>PSCredentialStore.Store</Name>
<ViewSelectedBy>
<TypeName>PSCredentialStore.Store</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Version</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Created</PropertyName>
</ListItem>
<ListItem>
<Label>PfxCertificate</Label>
<ScriptBlock>$_.PfxCertificate | Split-Path -Leaf</ScriptBlock>
</ListItem>
<ListItem>
<PropertyName>Thumbprint</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Type</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>PSCredentialStore.Certificate.Attribute</Name>
<ViewSelectedBy>
<TypeName>PSCredentialStore.Certificate.Attribute</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Country</PropertyName>
</ListItem>
<ListItem>
<PropertyName>State</PropertyName>
</ListItem>
<ListItem>
<PropertyName>City</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Organization</PropertyName>
</ListItem>
<ListItem>
<PropertyName>OrganizationalUnitName</PropertyName>
</ListItem>
<ListItem>
<PropertyName>CommonName</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@ -1,49 +0,0 @@
function Get-RandomKey {
<#
.SYNOPSIS
Returns a random key
.DESCRIPTION
You can use the key for further use with SecureStrings.
.PARAMETER Size
Define the key size. You can choose between 16, 24 and 32
.INPUTS
[None]
.OUTPUTS
Returns a Random key as [Byte[]] array.
.EXAMPLE
.\Get-RandomKey -Size 24
.NOTES
```
File Name : Get-RandomKey.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
```
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet(16, 24, 32)]
[string]$size
)
# Init the vars
[Byte[]]$Key = @()
$i = 0
while ($i -ne $size) {
$element = Get-Random -Minimum 0 -Maximum 255
Write-Debug ("The current element is {0}." -f $element)
$Key += $element
$i++
}
$Key
}

View File

@ -31,21 +31,17 @@ function Get-CredentialStoreItem {
$myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" $myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.NOTES .NOTES
``` - File Name : Get-CredentialStoreItem.ps1
File Name : Get-CredentialStoreItem.ps1 - Author : Messing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType([System.Management.Automation.PSCredential])] [OutputType([PSCredential])]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
@ -56,55 +52,77 @@ function Get-CredentialStoreItem {
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constand path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
} }
if ($Identifier -ne "") { process {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost if ($Identifier -ne "") {
} $CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
else { }
$CredentialName = $RemoteHost else {
} $CredentialName = $RemoteHost
}
if (Test-CredentialStore -Path $Path) { if (Test-CredentialStore -Shared -Path $Path) {
$CS = Get-CredentialStore -Path $Path $CS = Get-CredentialStore -Shared -Path $Path
$CSMembers = Get-Member -InputObject $CS $CSMembers = Get-Member -InputObject $CS
# Let`s first check if the given remote host exists as object property # Let's first check if the given remote host exists as object property
if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -eq $CredentialName)) { if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -contains $CredentialName)) {
if ($CS.Type -eq "Private") { if ($null -eq $CS.PfxCertificate) {
$CSItem = [ordered]@{ $Cert = Get-CSCertificate -Type $CS.Type -Thumbprint $CS.Thumbprint
User = $CS.$CredentialName.User }
Password = ConvertTo-SecureString -String $CS.$CredentialName.Password else {
$Cert = Get-PfxCertificate -FilePath $CS.PfxCertificate -ErrorAction Stop
}
$DecryptedKey = $Cert.PrivateKey.Decrypt(
[Convert]::FromBase64String($CS.$CredentialName.EncryptedKey),
[System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1
)
if (! $ExpandOutput.isPresent) {
[PSCredential]::new(
$CS.$CredentialName.User,
($CS.$CredentialName.Password | ConvertTo-SecureString -Key $DecryptedKey)
)
} }
} }
else { else {
$Key = Get-ChallengeFile $MsgParams = @{
$CSItem = [ordered]@{ ErrorAction = "Stop"
User = $CS.$CredentialName.User Message = "Could not find credentials for the given remote host: {0}" -f $RemoteHost
Password = ConvertTo-SecureString -String $CS.$CredentialName.Password -Key $Key
} }
Write-Error @MsgParams
} }
New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CSItem.User, $CSItem.Password
} }
else { else {
$MsgParams = @{ $MsgParams = @{
ErrorAction = "Stop" ErrorAction = "Stop"
Message = "Could not find credentials for the given remote host: {0}" -f $RemoteHost Message = "The given credential store ({0}) does not exist!" -f $Path
} }
Write-Error @MsgParams Write-Error @MsgParams
} }
} }
else {
$MsgParams = @{ end {
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
} }
} }

View File

@ -21,6 +21,10 @@ function New-CredentialStoreItem {
.PARAMETER Credential .PARAMETER Credential
You can provide credentials optionally as pre existing pscredential object. You can provide credentials optionally as pre existing pscredential object.
.PARAMETER Shared
Define the CredentialStore where you want to add the new item. Default is always personal but can be
changed to shared, or even shared with custom path.
.INPUTS .INPUTS
[None] [None]
@ -31,20 +35,16 @@ function New-CredentialStoreItem {
New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.NOTES .NOTES
``` - File Name : New-CredentialStoreItem.ps1
File Name : New-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
@ -55,82 +55,108 @@ function New-CredentialStoreItem {
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[pscredential]$Credential, [PSCredential]$Credential,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constand path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
} if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
} }
Write-Error @MessageParams elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
} if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
# Read the file content based on the given ParameterSetName }
$CSContent = Get-CredentialStore -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (-not($Credential)) {
$Credential = Get-Credential -Message $CredentialName
}
if ($Credential.UserName) {
if ($CSContent.Type -eq "Shared") {
$Key = Get-ChallengeFile
$encypted = ConvertFrom-SecureString -SecureString $Credential.Password -Key $Key
} }
else { }
$encypted = ConvertFrom-SecureString -SecureString $Credential.Password
} process {
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) { # Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Shared -Path $Path)) {
$MessageParams = @{ $MessageParams = @{
Message = "The given host already exists. Nothing to do here." Exception = [System.IO.FileNotFoundException]::new(
'Could not add anything into the given CredentialStore.'
)
ErrorAction = "Stop"
} }
Write-Warning @MessageParams Write-Error @MessageParams
}
$CSContent = Get-CredentialStore -Shared -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
} }
else { else {
$CredentialHash = [ordered]@{ $CredentialName = $RemoteHost
User = $Credential.UserName }
Password = $encypted
Creation = $CurrentDate if (-not($Credential)) {
$Credential = Get-Credential -Message $CredentialName
}
if ($Credential.UserName) {
if ($null -eq $CSContent.PfxCertificate) {
$Cert = Get-CSCertificate -Type $CSContent.Type -Thumbprint $CSContent.Thumbprint
} }
Add-Member -InputObject $CSContent -Name $CredentialName -MemberType NoteProperty -Value $CredentialHash else {
try { $Cert = Get-PfxCertificate -FilePath $CSContent.PfxCertificate -ErrorAction Stop
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
} }
catch [System.Exception] {
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
$MessageParams = @{ $MessageParams = @{
Message = "Couldn't add item into credential store!" Message = "The given host already exists. Nothing to do here."
ErrorAction = "Stop" }
Write-Warning @MessageParams
}
else {
$RSAKey = Get-RandomAESKey
$CredentialHash = [ordered]@{
User = $Credential.UserName
Password = ConvertFrom-SecureString -SecureString $Credential.Password -Key $RSAKey
Created = $CurrentDate
LastChange = $null
EncryptedKey = [Convert]::ToBase64String($Cert.PublicKey.Key.Encrypt($RSAKey, [System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1))
}
Add-Member -InputObject $CSContent -Name $CredentialName -MemberType NoteProperty -Value $CredentialHash
try {
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
}
catch {
$MessageParams = @{
Message = "Couldn't add item into credential store!"
ErrorAction = "Stop"
}
Write-Error @MessageParams
} }
Write-Error @MessageParams
} }
} }
} else {
else { $MessageParams = @{
$MessageParams = @{ Message = "Please Provide at least a valid user!"
Message = "Please Provide at least a valid user!" ErrorAction = "Stop"
ErrorAction = "Stop" }
Write-Error @MessageParams
} }
Write-Error @MessageParams
} }
end {
}
} }

View File

@ -27,15 +27,21 @@ function Remove-CredentialStoreItem {
[None] [None]
.EXAMPLE .EXAMPLE
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Remove-CredentialStoreItem -RemoteHost "esx01.myside.local"
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
.EXAMPLE
Remove-CredentialStoreItem -Shared -RemoteHost "esx01.myside.local"
.EXAMPLE
Remove-CredentialStoreItem -Shared -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.EXAMPLE
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local" -Identifier svc
.NOTES .NOTES
``` - File Name : Remove-CredentialStoreItem.ps1
File Name : Remove-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -43,9 +49,6 @@ function Remove-CredentialStoreItem {
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[string]$RemoteHost, [string]$RemoteHost,
@ -54,43 +57,62 @@ function Remove-CredentialStoreItem {
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constand path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
} if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
} }
Write-Error @MessageParams elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
} if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
# Read the file content based on the given ParameterSetName }
$CSContent = Get-CredentialStore -Path $Path
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
# We need to use the .NET Method because there is no easier way in PowerShell.
$CSContent.PSObject.Properties.Remove($CredentialName)
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
}
else {
$MessageParams = @{
Message = "The given CredentailStoreItem does not exist."
} }
Write-Warning @MessageParams
} }
process {
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Shared -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentialStore."
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore -Shared -Path $Path
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype NoteProperty) {
# We need to use the .NET Method because there is no easier way in PowerShell.
$CSContent.PSObject.Properties.Remove($CredentialName)
ConvertTo-Json -InputObject $CSContent -Depth 5 | Out-File -FilePath $Path -Encoding utf8
}
else {
$MessageParams = @{
Message = "The given CredentialStoreItem does not exist."
}
Write-Warning @MessageParams
}
}
end {
}
} }

View File

@ -4,6 +4,7 @@ function Set-CredentialStoreItem {
Changes the credentials for the given remote host in the store. Changes the credentials for the given remote host in the store.
.DESCRIPTION .DESCRIPTION
Use this function to update your already stored RemoteHost items.
.PARAMETER Path .PARAMETER Path
Define the store in which your given host entry already exists. Define the store in which your given host entry already exists.
@ -19,6 +20,9 @@ function Set-CredentialStoreItem {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems. can be decrypted across systems.
.PARAMETER Credential
Provided the new credentials you want to update inside the RemoteHost item.
.INPUTS .INPUTS
[None] [None]
@ -27,14 +31,14 @@ function Set-CredentialStoreItem {
.EXAMPLE .EXAMPLE
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.EXAMPLE
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
.NOTES .NOTES
``` - File Name : Set-CredentialStoreItem.ps1
File Name : Set-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -42,9 +46,6 @@ function Set-CredentialStoreItem {
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[string]$RemoteHost, [string]$RemoteHost,
@ -53,64 +54,89 @@ function Set-CredentialStoreItem {
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[PSCredential]$Credential,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constant path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
} if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
} }
Write-Error @MessageParams elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
} if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
$Creds = Get-Credential -Message $CredentialName
if ($Creds.UserName) {
if ($CSContent.Type -eq "Shared") {
$Key = Get-ChallengeFile
$encypted = ConvertFrom-SecureString -SecureString $Creds.Password -Key $Key
}
else {
$encypted = ConvertFrom-SecureString -SecureString $Creds.Password
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
$CSContent.$CredentialName.User = $Creds.UserName
$CSContent.$CredentialName.Password = $encypted
$CSContent.$CredentialName.Creation = $CurrentDate
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
}
else {
$MessageParams = @{
Message = "The given CredentailStoreItem does not exist."
} }
Write-Warning @MessageParams
} }
} }
Else {
$MessageParams = @{ process {
Message = "Please Provide at least a valid user!" # Lets do a quick test on the given CredentialStore.
ErrorAction = "Stop" if (-not(Test-CredentialStore -Shared -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
}
Write-Error @MessageParams
} }
Write-Error @MessageParams
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore -Shared -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (-not($Credential)) {
$Credential = Get-Credential -Message $CredentialName
}
if ($Credential.UserName) {
if ($null -eq $CSContent.PfxCertificate) {
$Cert = Get-CSCertificate -Type $CSContent.Type -Thumbprint $CSContent.Thumbprint
}
else {
$Cert = Get-PfxCertificate -FilePath $CSContent.PfxCertificate -ErrorAction Stop
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
$RSAKey = Get-RandomAESKey
$CSContent.$CredentialName.User = $Credential.UserName
$CSContent.$CredentialName.Password = ConvertFrom-SecureString -SecureString $Credential.Password -Key $RSAKey
$CSContent.$CredentialName.LastChange = $CurrentDate
$CSContent.$CredentialName.EncryptedKey = [Convert]::ToBase64String(
$Cert.PublicKey.Key.Encrypt(
$RSAKey,
[System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1
)
)
ConvertTo-Json -InputObject $CSContent -Depth 5 | Out-File -FilePath $Path -Encoding utf8
}
}
Else {
$MessageParams = @{
Message = "Please Provide at least a valid user!"
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
end {
} }
} }

View File

@ -1,4 +1,4 @@
function Test-CredentialStoreItem() { function Test-CredentialStoreItem {
<# <#
.SYNOPSIS .SYNOPSIS
Checks if the given RemoteHost identifier combination exists in the credential store. Checks if the given RemoteHost identifier combination exists in the credential store.
@ -37,11 +37,9 @@ function Test-CredentialStoreItem() {
} }
.NOTES .NOTES
``` - File Name : Test-CredentialStoreItem.ps1
File Name : Test-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -64,32 +62,48 @@ function Test-CredentialStoreItem() {
[switch]$Shared [switch]$Shared
) )
if ($PSCmdlet.ParameterSetName -eq "Private") { begin {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA # Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
} }
if ($Identifier -ne "") { process {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost if ($Identifier -ne "") {
} $CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
else {
$CredentialName = $RemoteHost
}
if (Test-CredentialStore -Path $Path) {
$CS = Get-CredentialStore -Path $Path
$CSMembers = Get-Member -InputObject $CS
if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -eq $CredentialName)) {
return $true
} }
else { else {
return $false $CredentialName = $RemoteHost
}
if (Test-CredentialStore -Shared -Path $Path) {
$CS = Get-CredentialStore -Shared -Path $Path
$CSMembers = Get-Member -InputObject $CS
if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -contains $CredentialName)) {
return $true
}
else {
return $false
}
}
else {
$MsgParams = @{
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
} }
} }
else {
$MsgParams = @{ end {
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
} }
} }

View File

@ -1,45 +1,36 @@
#
# Module manifest for module 'PSCredentialStore'
#
# Generated by: OCram85
#
# Generated on: 27.07.2017
#
@{ @{
# Script module or binary module file associated with this manifest. # Script module or binary module file associated with this manifest.
RootModule = 'PSCredentialStore' RootModule = 'PSCredentialStore.psm1'
# Version number of this module. # Version number of this module.
# Do not touch the version number. It gets replaced in the build process. ModuleVersion = '0.0.9999'
ModuleVersion = '0.0.0.9999'
# Supported PSEditions # Supported PSEditions
# CompatiblePSEditions = @() CompatiblePSEditions = 'Desktop', 'Core'
# ID used to uniquely identify this module # ID used to uniquely identify this module
GUID = '6800e192-9df8-4e30-b253-eb2c799bbe84' GUID = '6800e192-9df8-4e30-b253-eb2c799bbe84'
# Author of this module # Author of this module
Author = 'OCram85' Author = 'OCram85'
# Company or vendor of this module # Company or vendor of this module
CompanyName = '' CompanyName = ''
# Copyright statement for this module # Copyright statement for this module
Copyright = '(c) 2017 OCram85. All rights reserved.' Copyright = '(c) 2020 OCram85. All rights reserved.'
# Description of the functionality provided by this module # Description of the functionality provided by this module
Description = 'A simple credential manager to store and reuse multiple credential objects.' Description = 'A simple credential manager to store and reuse multiple credential objects.'
# Minimum version of the Windows PowerShell engine required by this module # Minimum version of the PowerShell engine required by this module
PowerShellVersion = '4.0' PowerShellVersion = '5.1'
# Name of the Windows PowerShell host required by this module # Name of the PowerShell host required by this module
# PowerShellHostName = '' # PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module # Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = '' # PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
@ -64,37 +55,51 @@
# TypesToProcess = @() # TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module # Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @() FormatsToProcess = @(
'Formats/PSCredential.Store.Format.ps1xml',
'Formats/PSCredentialStore.Certificate.Attribute.ps1xml'
)
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @() # NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @( FunctionsToExport = @(
# Connection Group # Certificate
'Get-CSCertificate',
'Import-CSCertificate',
'New-CSCertAttribute',
'New-CSCertificate',
'Test-CSCertificate',
'Use-CSCertificate',
# Pfx Certificate
# 'Get-CSPfxCertificate',
# 'Import-CSPfxCertificate',
# 'Test-CSPfxCertificate',
# Connection
'Connect-To', 'Connect-To',
'Disconnect-From', 'Disconnect-From',
# Item Group 'Test-CSConnection',
# Item
'Get-CredentialStoreItem', 'Get-CredentialStoreItem',
'Set-CredentialStoreItem',
'New-CredentialStoreItem', 'New-CredentialStoreItem',
'Remove-CredentialStoreItem', 'Remove-CredentialStoreItem',
'Set-CredentialStoreItem',
'Test-CredentialStoreItem', 'Test-CredentialStoreItem',
# Store Group # Store
'Get-CredentialStore', 'Get-CredentialStore',
'New-CredentialStore', 'New-CredentialStore',
'Test-CredentialStore' 'Test-CredentialStore'
) )
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @() CmdletsToExport = @()
# Variables to export from this module # Variables to export from this module
VariablesToExport = '*' VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @() AliasesToExport = @()
# DSC resources to export from this module # DSC resources to export from this module
# DscResourcesToExport = @() # DscResourcesToExport = @()
@ -106,33 +111,40 @@
# FileList = @() # FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{ PrivateData = @{
PSData = @{ PSData = @{
# Tags applied to this module. These help with module discovery in online galleries. # Tags applied to this module. These help with module discovery in online galleries.
Tags = @('CredentialStore', Tags = 'CredentialStore', 'CredentialManager'
'CredentialManager'
)
# A URL to the license for this module. # A URL to the license for this module.
LicenseUri = 'https://github.com/OCram85/PSCredentialStore/blob/master/LICENSE' LicenseUri = 'https://github.com/OCram85/PSCredentialStore/blob/master/LICENSE'
# A URL to the main website for this project. # A URL to the main website for this project.
ProjectUri = 'https://github.com/OCram85/PSCredentialStore' ProjectUri = 'https://github.com/OCram85/PSCredentialStore'
# A URL to an icon representing this module. # A URL to an icon representing this module.
# IconUri = '' IconUri = 'https://raw.githubusercontent.com/OCram85/PSCredentialStore/master/assets/logo256.png'
# ReleaseNotes of this module # ReleaseNotes of this module
ReleaseNotes = 'This is a pre-release version!. Do not use in production!' ReleaseNotes = 'See https://github.com/OCram85/PSCredentialStore/releases page for details.'
# Prerelease string of this module
#Prerelease = 'preview'
# Flag to indicate whether the module requires explicit user acceptance for install/update
# RequireLicenseAcceptance = $false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable } # End of PSData hashtable
} # End of PrivateData hashtable } # End of PrivateData hashtable
# HelpInfo URI of this module # HelpInfo URI of this module
HelpInfoURI = 'https://github.com/OCram85/PSCredentialStore' HelpInfoURI = 'https://github.com/OCram85/PSCredentialStore'
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = '' # DefaultCommandPrefix = ''

View File

@ -1,10 +1,18 @@
$Items = (Get-ChildItem -Path ("{0}\*.ps1" -f $PSScriptRoot ) -Recurse ).FullName | Where-Object { #region module-definition
#endregion module-definition
Set-Variable -Name "CSVersion" -Value "2.0.0" -Option Constant -Scope 'Script' -ErrorAction Stop
#region dot-sourcing
# dot-sourcing all module functions. The export is handled via manifest file.
$Items = (Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath '*.ps1') -Recurse ).FullName | Where-Object {
$_ -notmatch "(Classes|Init)" $_ -notmatch "(Classes|Init)"
} }
ForEach ($Item in $Items) { foreach ($Item in $Items) {
# Write-Verbose ("dot sourcing file {0}" -f $Item) # Write-Verbose ("dot sourcing file {0}" -f $Item)
. $Item . $Item
} }
#endregion dot-sourcing
# Exports are now controlled by module manifest
# Export-ModuleMember -Function *

View File

@ -0,0 +1,81 @@
function Get-CSPfxCertificate {
<#
.SYNOPSIS
Returns the certificate object given by thumbprint.
.DESCRIPTION
You can use this function to get a stored certificate. Search for the object by its unique thumbprint.
.PARAMETER Thumbprint
Provide one or more thumbprints.
.PARAMETER StoreName
Select the store name in which you want to search the certificates.
.PARAMETER StoreLocation
Select between the both available locations CurrentUser odr LocalMachine.
.INPUTS
[string]
.OUTPUTS
[System.Security.Cryptography.X509Certificates.X509Certificate2[]]
.EXAMPLE
Get-CSPfxCertificate -Thumbprint '12345678' -StoreName 'My' -StoreLocation 'CurrentUser'
.NOTES
- File Name : Get-CSPfxCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[string[]]$Thumbprint,
[Parameter(Mandatory = $false)]
[ValidateSet(
'AddressBook',
'AuthRoot',
'CertificateAuthority',
'Disallowed',
'My',
'Root',
'TrustedPeople',
'TrustedPublisher'
)]
[string]$StoreName = 'My',
[Parameter(Mandatory = $false)]
[ValidateSet(
'CurrentUser',
'LocalMachine'
)]
[string]$StoreLocation = 'CurrentUser'
)
begin {
$Store = [System.Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
try {
$Store.Open('ReadOnly')
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
}
}
process {
foreach ($Thumb in $Thumbprint) {
Write-Output $Store.Certificates | Where-Object { $_.Thumbprint -eq $Thumb }
}
}
end {
$Store.Close()
}
}

View File

@ -0,0 +1,61 @@
function Get-DefaultCredentialStorePath {
<#
.SYNOPSIS
Returns the default CredentialStore path based on the current OS.
.DESCRIPTION
This is a low level helper function.
.INPUTS
[None]
.OUTPUTS
[string]
.EXAMPLE
$Path = Get-DefaultCredentialStorePath
.NOTES
- File Name : Get-DefaultCredentialStorePath.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory = $false)]
[switch]$Shared
)
begin { }
process {
if ($Shared.IsPresent) {
if ($IsLinux) {
return Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
}
if ($IsMacOS) {
return Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
}
elseif (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
return Join-Path -Path $env:ProgramData -ChildPath 'PSCredentialStore/CredentialStore.json'
}
}
else {
if ($IsLinux) {
return Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
}
if ($IsMacOS) {
return Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
}
elseif (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
return Join-Path -Path $env:AppData -ChildPath 'CredentialStore.json'
}
}
}
end { }
}

View File

@ -0,0 +1,29 @@
function Get-ModuleBase {
<#
.SYNOPSIS
Returns the base path of the current module.
.DESCRIPTION
This is just a wrapper for enabling pester tests.
.OUTPUTS
Returns the base path as string
.NOTES
- File Name : Get-ModuleBase.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType()]
param()
begin { }
process {
return $MyInvocation.MyCommand.Module.ModuleBase
}
end { }
}

View File

@ -0,0 +1,44 @@
function Get-RandomAESKey {
<#
.SYNOPSIS
Generate a new 32-byte AES key.
.DESCRIPTION
Uses the System.Security.Cryptography namespace for random aes key generation.
.INPUTS
[None]
.OUTPUTS
[byte[]]
.EXAMPLE
.\Get-RandomAESKey
.NOTES
- File Name : Get-RandomAESKey.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([byte[]])]
param()
begin { }
process {
$key = [byte[]]::new(32)
$rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
$rng.GetBytes($key)
Write-Output $key
if ($null -ne $key) {
[array]::Clear($key, 0, $key.Length)
}
}
end { }
}

View File

@ -0,0 +1,44 @@
function Get-TempDir {
<#
.SYNOPSIS
Returns the valid temp dir of the current OS
.DESCRIPTION
Returns the valid temp dir of the current OS.
.INPUTS
[None]
.OUTPUTS
[string]
.EXAMPLE
Get-TempDir
.NOTES
- File Name : Get-TempDir.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([string])]
param()
begin {
}
process {
if ($IsLinux) {
return (Resolve-Path -Path '/tmp/').Path
}
if ($IsMacOS) {
return (Resolve-Path -Path '/tmp/').Path
}
elseif (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
return (Resolve-Path -Path $env:TEMP).Path
}
}
end {
}
}

View File

@ -0,0 +1,112 @@
function Import-CSPfxCertificate {
<#
.SYNOPSIS
Adds a given pfx certificate file to current user's personal certificate store.
.DESCRIPTION
This function is used to import existing pfx certificate files. The Import-PFXCertificate cmdlet from the
PKI module imports the certificate into a deprecated store. Thus you can't read the private key afterwards or
using it for decrypting data.
.PARAMETER Path
Path to an existing *.pfx certificate file.
.PARAMETER StoreName
Additionally you change change the store where you want the certificate into.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
Import-CSPfxCertificate -Path (Join-Path -Path $Env:APPDATA -ChildPath '/PSCredentialStore.pfx')
.NOTES
File Name : Import-CSPfxCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory = $false)]
[ValidateSet(
'AddressBook',
'AuthRoot',
'CertificateAuthority',
'Disallowed',
'My',
'Root',
'TrustedPeople',
'TrustedPublisher'
)]
[string]$StoreName = 'My',
[Parameter(Mandatory = $false)]
[ValidateSet(
'CurrentUser',
'LocalMachine'
)]
[string]$StoreLocation = 'CurrentUser',
[Parameter(Mandatory = $false)]
[ValidateSet(
'ReadOnly',
'ReadWrite',
'MaxAllowed',
'OpenExistingOnly',
'IncludeArchived'
)]
[string]$OpenFlags = 'ReadWrite'
)
begin {
$Store = [System.Security.Cryptography.X509Certificates.X509Store]::new($StoreName, $StoreLocation)
try {
$Store.Open($OpenFlags)
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
}
}
process {
try {
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(
$Path,
$null,
(
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable -bor
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
)
)
if (Test-CSPfxCertificate -Thumbprint $cert.Thumbprint) {
Write-Warning -Message ('The certificate with thumbprint {0} is already present!' -f $cert.Thumbprint)
}
else {
$Store.Add($cert)
}
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.Exception]::new(
'Could not read or add the pfx certificate!'
)
}
Write-Error @ErrorParams
}
}
end {
$Store.Close()
}
}

View File

@ -40,11 +40,9 @@ function Resolve-Dependency {
} }
.NOTES .NOTES
``` - File Name : ResolveDependency.ps1
File Name : ResolveDependency.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -53,11 +51,12 @@ function Resolve-Dependency {
[CmdletBinding()] [CmdletBinding()]
param ( param (
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Name [string]$Name
) )
begin { begin {
$ModuleRootDir = $MyInvocation.MyCommand.Module.ModuleBase $ModuleRootDir = Get-ModuleBase
$DepFilePath = Join-Path -Path $ModuleRootDir -ChildPath "Dependency.json" $DepFilePath = Join-Path -Path $ModuleRootDir -ChildPath "Dependency.json"
if (Test-Path -Path $DepFilePath) { if (Test-Path -Path $DepFilePath) {
$Dependency = Get-Content -Path $DepFilePath -Raw -Encoding UTF8 | ConvertFrom-Json $Dependency = Get-Content -Path $DepFilePath -Raw -Encoding UTF8 | ConvertFrom-Json
@ -65,16 +64,21 @@ function Resolve-Dependency {
else { else {
Write-Warning ("Could not find the dependency file: {0}" -f $DepFilePath) Write-Warning ("Could not find the dependency file: {0}" -f $DepFilePath)
} }
$res = @()
} }
process { process {
$SelectedDependency = $Dependency.Optional | Where-Object {$_.Name -match $Name} $SelectedDependency = $Dependency.Optional | Where-Object { $_.Name -match $Name }
# return true if there is no dependency defined
if ($null -eq $SelectedDependency) {
return $true
}
$res = @()
foreach ($Module in $SelectedDependency.Modules) { foreach ($Module in $SelectedDependency.Modules) {
$res += Test-Module -Name $Module $res += Test-Module -Name $Module
} }
if ($res -contains $false) { # return false if there was not module at all
if (($res -contains $false) -or ($res.Count -eq 0)) {
return $false return $false
} }
else { else {

View File

@ -0,0 +1,86 @@
function Test-CSPfxCertificate {
<#
.SYNOPSIS
Tests if the given certificate exists in a store.
.DESCRIPTION
Use this function to ensure if a certificate is already imported into a given store.
.PARAMETER Thumbprint
Provide one or more thumbprints.
.PARAMETER StoreName
Select the store name in which you want to search the certificates.
.PARAMETER StoreLocation
Select between the both available locations CurrentUser odr LocalMachine.
.INPUTS
[None]
.OUTPUTS
[bool]
.EXAMPLE
Test-CSPfxCertificate -Thumbprint '12345678' -StoreName 'My' -StoreLocation 'CurrentUser'
.NOTES
File Name : Test-CSPfxCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[string]$Thumbprint,
[Parameter(Mandatory = $false)]
[ValidateSet(
'AddressBook',
'AuthRoot',
'CertificateAuthority',
'Disallowed',
'My',
'Root',
'TrustedPeople',
'TrustedPublisher'
)]
[string]$StoreName = 'My',
[Parameter(Mandatory = $false)]
[ValidateSet(
'CurrentUser',
'LocalMachine'
)]
[string]$StoreLocation = 'CurrentUser'
)
begin {
$Store = [System.Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
try {
$Store.Open('ReadOnly')
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
}
}
process {
$Cert = $Store.Certificates | Where-Object { $_.Thumbprint -eq $Thumbprint }
if ($null -eq $Cert) {
return $false
}
else {
return $true
}
}
end {
$Store.Close()
}
}

View File

@ -34,11 +34,9 @@ function Test-Module {
.\Test-Dependency -Name 'VMware.PowerCLI' -Type 'Module' -StopIfFails .\Test-Dependency -Name 'VMware.PowerCLI' -Type 'Module' -StopIfFails
.NOTES .NOTES
``` - File Name : Test-Module.ps1
File Name : Get-RandomKey.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -50,10 +48,6 @@ function Test-Module {
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Name, [string]$Name,
[Parameter(Mandatory = $false)]
[ValidateSet('Module', 'PSSnapin', 'Custom')]
[string]$Type = 'Module',
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$MessagePattern = @" [string]$MessagePattern = @"
@ -62,45 +56,22 @@ Could not find the required {0} called {1}. Please install the required {0} to r
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[switch]$StopIfFails [switch]$StopIfFails
) )
begin { begin { }
}
process { process {
$Message = $MessagePattern -f $Type, $Name $Message = $MessagePattern -f $Type, $Name
Write-Debug $Message Write-Debug $Message
switch ($Type) {
'Module' {
if (Get-Module -Name $Name -ListAvailable) {
return $true
}
else {
if ($StopIfFails) {
Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
}
return $false
}
}
'PSSnapin' { if (Get-Module -Name $Name -ListAvailable) {
if (Get-PSSnapin -Name $Name -Registered) { return $true
return $true }
} else {
else { if ($StopIfFails) {
if ($StopIfFails) { Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
return $false
}
}
}
'Custom' {
Throw 'Custom tests are not implemented yet!'
} }
return $false
} }
} }
end { end { }
}
} }

View File

@ -25,46 +25,62 @@ function Get-CredentialStore {
$CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json" $CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json"
.NOTES .NOTES
``` - File Name : Get-CredentialStore.ps1
File Name : Get-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType("PSCredentialStore.Store")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [string]$Path,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared [switch]$Shared
) )
if ($PSCmdlet.ParameterSetName -eq 'Private') { begin { }
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
if (Test-CredentialStore -Path $Path) { process {
try { # Set the CredentialStore for private, shared or custom mode.
$FileContent = Get-Content -Path $Path -Raw Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
ConvertFrom-Json $FileContent if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
} }
catch [System.Exception] { elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
if (Test-CredentialStore -Path $Path -Shared) {
try {
$FileContent = Get-Content -Path $Path -Raw
$CS = ConvertFrom-Json $FileContent
$CS.PSObject.TypeNames.Insert(0, "PSCredentialStore.Store")
return $CS
}
catch [System.Exception] {
$MessageParams = @{
Message = "Unknown CredentialStore format. Invalid JSON file."
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
else {
$MessageParams = @{ $MessageParams = @{
Message = "Unknown CredentialStore format. Invalid JSON file." Message = "Could not find the CredentialStore."
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
} }
} }
else {
$MessageParams = @{ end { }
Message = "Could not find the CredentialStore."
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
} }

View File

@ -18,11 +18,21 @@ function New-CredentialStore {
.PARAMETER Force .PARAMETER Force
Use this switch to reset an existing store. The complete content will be wiped. Use this switch to reset an existing store. The complete content will be wiped.
.PARAMETER SkipPFXCertCreation
You can skip the pfx certificate creation process. This makes sense if you have a previously created cert or want to
import a cert in cross-platform environments.
.Parameter UseCertStore
Instead of using a plain pfx file beside your CredentialStore file you can import it into the user or machine
certificate store. In this case the system itself secures the cert and you don't hat to set custom NTFS
permissions so secure your shared certificate.
.INPUTS .INPUTS
[None] [None]
.OUTPUTS .OUTPUTS
[None] ['PSCredentialStore.Store'] Returns the recently created CredentialStore object if the -PassThru parameter
was given.
.EXAMPLE .EXAMPLE
New-CredentialStore New-CredentialStore
@ -41,72 +51,208 @@ function New-CredentialStore {
# Creates a new shared CredentialStore in the given location. # Creates a new shared CredentialStore in the given location.
.NOTES .NOTES
``` - File Name : New-CredentialStore.ps1
File Name : New-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = "Private")]
[OutputType("PSCredentialStore.Store")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared, [switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData, [System.IO.FileInfo]$Path,
[Parameter(Mandatory = $false, ParameterSetName = "Private")] [Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Force [Switch]$Force,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$PassThru,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$SkipPFXCertCreation,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$UseCertStore
) )
# Lets get the current Date in a human readable format. begin {
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S" # Lets get the current Date in a human readable format.
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
# Set latest Credential Store version # Set latest Credential Store version
Set-Variable -Name "CSVersion" -Value "1.2.0" -Option Constant # Set-Variable -Name "CSVersion" -Value "2.0.0" -Option Constant -Scope
# Set the CredentialStore path for private mode. # test if the path input is a valid file path
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName) if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Path')) {
if ($PSCmdlet.ParameterSetName -eq "Private") { if ($Path.Attributes -contains 'Directory') {
$Path = "{0}\CredentialStore.json" -f $Env:APPDATA $ErrorParams = @{
} ErrorAction = 'Stop'
Exception = [System.IO.InvalidDataException]::new(
# Test if in the given store already a CredentialStore exists. 'Please provide a full path containing the credential store file name with the .json extension!'
Write-Verbose "Test if there is already a credential store." )
if ((Test-CredentialStore -Path $Path) -and ($Force -ne $true)) { }
$MessageParam = @{ Write-Error @ErrorParams
Message = "The given file already exists. Use the 'Force' switch to override the existing store." }
ErrorAction = "Stop" elseif ( ($null -eq $Path.Extension) -or ($Path.Extension -ne '.json')) {
} $ErrorParams = @{
Write-Error @MessageParam ErrorAction = 'Stop'
} Exception = [System.IO.InvalidDataException]::new(
# We need to use the IDictionary to keep the property sorting in the object. 'Your provided path does not contain the required file extension .json !'
$ObjProperties = [ordered]@{ )
Version = $CSVersion }
Creation = $CurrentDate Write-Error @ErrorParams
} }
if ($PSCmdlet.ParameterSetName -eq "Shared") {
$ObjProperties.Type = "Shared"
# Check if a ChallengeFile already exists. We don't want to overide it.
# Otherwise previous created CredentialStores couln't be decrypted anymore.
if (-not (Test-ChallengeFile)) {
Set-ChallengeFile
} }
} }
else {
$ObjProperties.Type = "Private" process {
# Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
# Test if in the CredentialStore already exists.
Write-Verbose "Test if there is already a credential store."
if ((Test-Path -Path $Path) -and ($Force -ne $true)) {
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.InvalidOperationException]::new(
'The given file already exists. Use the -Force switch to override the existing store.'
)
}
Write-Error @ErrorParams
}
if (! $SkipPFXCertCreation.IsPresent) {
$CRTParams = @{
Country = 'DE'
State = 'PSCredentialStore'
City = 'PSCredentialStore'
Organization = 'PSCredentialStore'
OrganizationalUnitName = $PSCmdlet.ParameterSetName
CommonName = 'PSCredentialStore'
}
$CRTAttribute = New-CSCertAttribute @CRTParams
# If we are working with a ne shared store we have to create the location first.
# Otherwise openssl fails with unknown path
$StoreHome = Split-Path -Path $Path -Parent
if (! (Test-Path -Path $StoreHome)) {
New-Item -ItemType Directory -Path $StoreHome -ErrorAction Stop
}
$PfxParams = @{
CRTAttribute = $CRTAttribute
KeyName = Join-Path -Path $StoreHome -ChildPath 'private.key'
CertName = Join-Path -Path $StoreHome -ChildPath 'PSCredentialStore.pfx'
ErrorAction = 'Stop'
Confirm = $false
}
# test if there is already a cert
if ((Test-Path $PfxParams.CertName) -and (! $Force.IsPresent)) {
$ErrorParams = @{
Exception = [System.IO.InvalidDataException]::new(
'There is already a PfxCertificate for a private CredentialStore!'
)
ErrorAction = 'Stop'
}
Write-Error @ErrorParams
}
try {
New-CSCertificate @PfxParams
}
catch {
$_.Exception.Message | Write-Error
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.Exception]::new(
'Could not create the private PfXCertificate!'
)
}
Write-Error @ErrorParams
}
try {
$FreshCert = Get-PfxCertificate -FilePath $PfxParams.CertName -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
$_.Exception.Message | Write-Error
Write-Error -Message 'Could not read the new PfxCertificate.' -ErrorAction Stop
}
}
# We need to use the IDictionary to keep the property sorting in the object.
$ObjProperties = [ordered]@{
PSTypeName = 'PSCredentialStore.Store'
Version = $CSVersion
Created = $CurrentDate
PfxCertificate = $null
Thumbprint = $null
Type = $null
}
if ($PSCmdlet.ParameterSetName -eq "Shared") {
$ObjProperties.Type = "Shared"
}
else {
$ObjProperties.Type = "Private"
}
if (! $SkipPFXCertCreation.IsPresent) {
$ObjProperties.Thumbprint = $FreshCert.Thumbprint
if ($UseCertStore.IsPresent) {
Write-Verbose 'Importing new PFX certificate file...'
Import-CSCertificate -Type $ObjProperties.Type -Path $PfxParams.CertName
}
else {
$ObjProperties.PfxCertificate = $PfxParams.CertName
}
}
$CredentialStoreObj = [PSCustomObject]$ObjProperties
try {
$JSON = ConvertTo-Json -InputObject $CredentialStoreObj -ErrorAction Stop
$JSON | Out-File -FilePath $Path -ErrorAction Stop -Force
}
catch {
$_.Exception.Message | Write-Error
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.IO.IOException]::new(
'Unable to convert or write the CredentialStore'
)
}
Write-Error @ErrorParams
}
if ($PassThru.IsPresent) {
return $CredentialStoreObj
}
} }
# Create a new object for easy conversion into a json file
$CredentialStoreObj = New-Object -TypeName psobject -Property $ObjProperties end {
try {
ConvertTo-Json -InputObject $CredentialStoreObj | Out-File -FilePath $Path
}
catch [System.Exception] {
$_.Exception | Format-List -Force | Out-String | Write-Error -ErrorAction Stop
} }
} }

View File

@ -14,49 +14,54 @@ function Test-CredentialStore {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems. can be decrypted across systems.
.EXAMPLE
Test-CredentialStore -eq $true
.NOTES .NOTES
``` - File Name : Test-CredentialStore.ps1
File Name : Test-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData, [string]$Path,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared [switch]$Shared
) )
begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set latest Credential Store version
$Path = "{0}\CredentialStore.json" -f $Env:APPDATA #Set-Variable -Name "CSVersion" -Value "2.0.0" -Option Constant
} }
# Set latest Credential Store version process {
Set-Variable -Name "CSVersion" -Value "1.2.0" -Option Constant # Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if (Test-Path $Path) { if ($PSCmdlet.ParameterSetName -eq "Private") {
Write-Verbose "CredentialStore in given path found." $Path = Get-DefaultCredentialStorePath
# try tor read the store. Removed the Get-CredentialStore function to avoid recursive calls.
try {
$FileContent = Get-Content -Path $Path -Raw
$CSContent = ConvertFrom-Json $FileContent
} }
catch { elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
Write-Warning "Could not read or convert the given CredentialStore." if (!($PSBoundParameters.ContainsKey('Path'))) {
Return $False $Path = Get-DefaultCredentialStorePath -Shared
}
} }
Return $True Write-Verbose -Message ("Path is: {0}" -f $Path)
if (Test-Path $Path) {
Write-Verbose "CredentialStore in given path found."
return $true
}
else {
Write-Verbose "The given CredentialStore does not exist!"
return $false
}
} }
Else {
Write-Verbose "The given CredentialStore does not exist!" end { }
Return $False
}
} }

BIN
src/Vendor/libressl255/LICENSE (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.dll (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.exp (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.lib (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.pdb (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.dll (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.exp (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.lib (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.pdb (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.dll (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.exp (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.lib (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.pdb (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/ocspcheck.exe (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/openssl.exe (Stored with Git LFS) vendored Normal file

Binary file not shown.

245
src/openssl.conf Normal file
View File

@ -0,0 +1,245 @@
#
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.
#
# This definition stops the following lines choking if HOME isn't
# defined.
HOME = .
RANDFILE = $ENV::HOME/.rnd
# Extra OBJECT IDENTIFIER info:
#oid_file = $ENV::HOME/.oid
oid_section = new_oids
# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions =
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)
[ new_oids ]
# We can add new OIDs in here for use by 'ca' and 'req'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
####################################################################
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem # The private key
RANDFILE = $dir/private/.rand # private random number file
x509_extensions = usr_cert # The extentions to add to the cert
# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crl_extensions = crl_ext
default_days = 365 # how long to certify for
default_crl_days = 30 # how long before next CRL
default_md = md5 # which md to use.
preserve = no # keep passed DN ordering
# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_match
# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret
# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix : PrintableString, BMPString.
# utf8only: only UTF8Strings.
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: current versions of Netscape crash on BMPStrings or UTF8Strings
# so use this option with caution!
string_mask = nombstr
# req_extensions = v3_req # The extensions to add to a certificate request
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = DE
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = BW
localityName = Locality Name (eg, city)
localityName_default = PSCredentialStore
0.organizationName = Organization Name (eg, company)
0.organizationName_default = PSCredentialStore
# we can do this but it is not needed normally :-)
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
#organizationalUnitName_default = PSCRedentialStore
commonName = Common Name (eg, YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 40
# SET-ex3 = SET extension number 3
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 0
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
# These extensions are added when 'ca' signs a request.
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints = CA:FALSE
# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.
# This is OK for an SSL server.
# nsCertType = server
# For an object signing certificate this would be used.
# nsCertType = objsign
# For normal client use this is typical
# nsCertType = client, email
# and for everything including object signing:
# nsCertType = client, email, objsign
# This is typical in keyUsage for a client certificate.
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, codeSigning
# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# Copy subject details
# issuerAltName=issuer:copy
#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, codeSigning
[ v3_ca ]
# Extensions for a typical CA
# PKIX recommendation.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
# This is what PKIX recommends but some broken software chokes on critical
# extensions.
#basicConstraints = critical,CA:true
# So we do this instead.
basicConstraints = CA:true
# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign
# Some might want this also
# nsCertType = sslCA, emailCA
# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy
# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF
[ crl_ext ]
# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy
authorityKeyIdentifier = keyid:always,issuer:always

View File

@ -0,0 +1,17 @@
$RepoRoot = (Get-Item -Path (Get-GitDirectory) -Force).Parent | Select-Object -ExpandProperty 'FullName'
Write-Verbose -Message ('RepoRoot: {0}' -f $RepoRoot) -Verbose
$ManifestFilePath = Join-Path -Path $RepoRoot -ChildPath '/src/PSCredentialStore.psd1'
Write-Verbose -Message ("ManifestFilePath: {0}" -f $ManifestFilePath) -Verbose
Describe "Pre-Flight module tests" {
Context "Manifest file related" {
It "Test the parsed file itself" {
{ Test-ModuleManifest -Path $ManifestFilePath -Verbose } | Should -Not -Throw
}
}
Context "Module consistency tests" {
It "Importing should work" {
{ Import-Module -Name $ManifestFilePath -Global -Force -Verbose } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,7 @@
Describe "New-CSCertAttribute" {
Context "Basis Tests" {
It "Test1: Should not throw " {
{ New-CSCertAttribute -Country 'DE' -State 'BW' -City 'KA' -Organization 'IT' -OrganizationalUnitName'' -CommonName 'Mycert' } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,15 @@
Describe "New-CSCertificate" {
Context "Basic Tests" {
It "Test1: Should not throw" {
$attribs = New-CSCertAttribute -Country 'DE' -State 'BW' -City 'KA' -Organization 'IT' -OrganizationalUnitName'' -CommonName 'Mycert'
$CertAttribs = @{
CRTAttribute = $attribs
KeyName = Join-Path -Path (Get-TempDir) -ChildPath '/foo.key'
CertName = Join-Path -Path (Get-TempDir) -ChildPath '/cert.pfx'
}
{ New-CSCertificate @CertAttribs } | Should -Not -Throw
}
}
}

View File

@ -1,65 +0,0 @@
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# $RepoRoot = (Get-Item -Path $here).Parent.Parent.FullName
$RepoRoot = (Get-GitDirectory).replace('\.git', '')
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude ".\tests\" -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
# load additional functions defined in the repository. Replace the expression <FunctionName>.
. (Get-ChildItem -Path $RepoRoot -Filter "Test-CredentialStore.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "New-CredentialStore.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Get-CredentialStore.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Get-CredentialStoreItem.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Test-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Get-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Set-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Get-RandomKey.ps1" -Recurse).FullName
#endregion HEADER
Describe "New-CredentialStoreItem" {
Context "Private Credential Store tests" {
It "Test1: Add entry to existing private store." {
If (-not (Test-CredentialStore)) {
New-CredentialStore
}
[String]$tmp = (65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}
$tmp = $tmp.Replace(' ', '')
$tmpUser = "MyUser"
$tmpPwd = "fooobarysdfsfs" | ConvertTo-SecureString -AsPlainText -Force
$creds = New-Object -TypeName PsCredential -ArgumentList $tmpUser, $tmpPwd
New-CredentialStoreItem -RemoteHost $tmp -Credential $creds
# Had to remove the `{ <exp> } | Shoud Not Throw` because the return would be empty.
$content = Get-CredentialStoreItem -RemoteHost $tmp
$content.UserName | Should Be "MyUser"
#Cleanup Temp entry
$CS = Get-CredentialStore
$CS.PSObject.Properties.Remove($tmp)
ConvertTo-Json -InputObject $CS | Out-File -FilePath ("{0}\CredentialStore.json" -f $env:AppData)
}
}
Context "Test with new shared Credential Store" {
It "Test2: Create new RemoteHost entry" {
# prepare test environment
$tmpCS = 'C:\CredentialStore.json'
New-CredentialStore -Shared -Path $tmpCS
$UserName = "myuser"
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
$mycreds = New-Object -TypeName PSCredential -ArgumentList $UserName, $Password
$RemoteHost = "foobar"
{ New-CredentialStoreItem -Path $tmpCS -RemoteHost $RemoteHost -Credential $mycreds -Shared } | Should Not Throw
$tmpCS = Get-Content -Path $tmpCS -Raw | ConvertFrom-Json
$res = Get-Member -InputObject $tmpCS -Name $RemoteHost -Membertype Properties
$res.Name | Should Be $RemoteHost
}
}
}

View File

@ -0,0 +1,109 @@
Describe "New-CredentialStoreItem" {
Context "Private Credential Store tests" {
It "Test1: Add entry to existing private store." {
# Creat a fresh CredentialStore first
New-CredentialStore -Force
[String]$tmp = (65..90) + (97..122) | Get-Random -Count 5 | ForEach-Object { [char]$_ }
$tmp = $tmp.Replace(' ', '')
$tmpUser = "MyUser"
$tmpPwd = "fooobarysdfsfs" | ConvertTo-SecureString -AsPlainText -Force
$creds = [PSCredential]::new($tmpUser, $tmpPwd)
New-CredentialStoreItem -RemoteHost $tmp -Credential $creds
# Had to remove the `{ <exp> } | Shoud Not Throw` because the return would be empty.
$content = Get-CredentialStoreItem -RemoteHost $tmp
$content.UserName | Should -Be "MyUser"
#Cleanup Temp entry
$CS = Get-CredentialStore
$CS.PSObject.Properties.Remove($tmp)
ConvertTo-Json -InputObject $CS | Out-File -FilePath (Get-DefaultCredentialStorePath)
}
}
Context "Test with new shared Credential Store" {
It "Test2: Create new RemoteHost entry" {
# prepare test environment
$tmpCS = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
New-CredentialStore -Shared -Path $tmpCS -Force
$UserName = "myuser"
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
$mycreds = [PSCredential]::new($UserName, $Password)
$RemoteHost = "foobar"
{ New-CredentialStoreItem -Shared -Path $tmpCS -RemoteHost $RemoteHost -Credential $mycreds } | Should -Not -Throw
$tmpCS = Get-Content -Path $tmpCS -Raw | ConvertFrom-Json
$res = Get-Member -InputObject $tmpCS -Name $RemoteHost -Membertype Properties
$res.Name | Should -Be $RemoteHost
}
It "Adds Item with identifier to shared store" {
$tmpCS = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
New-CredentialStore -Shared -Path $tmpCS -Force
$UserName = "myuser"
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
$mycreds = [PSCredential]::new($UserName, $Password)
$RemoteHost = "foobar2"
New-CredentialStoreItem -Shared -Path $tmpCS -RemoteHost $RemoteHost -Credential $mycreds -Identifier 'Foo'
$writtenItem = Get-CredentialStoreItem -Shared -Path $tmpCS -RemoteHost $RemoteHost -Identifier 'Foo'
($writtenItem.UserName -eq $UserName) -and ($writtenItem.Password.Length -gt 0) | Should -Be $true
}
}
Context "Test optional parameter lookup" {
It "Test missing Credential" {
function global:Get-Credential ([string]$Message) {
$UserName = 'testuser'
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
return [PSCredential]::new($UserName, $Password)
}
$tmpCS = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
New-CredentialStoreItem -Path $tmpCs -Shared -RemoteHost 'foobar3'
$writtenItem = Get-CredentialStoreItem -Path $tmpCS -Shared -RemoteHost 'foobar3'
$writtenItem.UserName | Should -Be "testuser"
Remove-Item -Path 'Function:\Get-Credential'
}
}
Context "General Exception handling" {
Mock Test-CredentialStore { return $false }
It "Missing CredentialStore should throw" {
{ New-CredentialStoreItem -Shared -Path 'C:\missingStore.json' -RemoteHost 'notrelevant' } | Should -Throw "Could not add anything"
}
}
Context "Testing pipeline paramter" {
It "Add the item with credential value from pipe" {
$UserName = 'pipeUser'
$Password = ConvertTo-SecureString -String "pipePasswd" -AsPlainText -Force
{ [PSCredential]::new($UserName, $Password) | New-CredentialStoreItem -RemoteHost 'PipeHost' } | Should -Not -Throw
}
It "Testing written item" {
(Get-CredentialStoreItem -RemoteHost 'PipeHost').UserName | Should -Be 'pipeUser'
}
}
Context "Testing items with certficiate store" {
It "Create item in new store with cert store link" {
New-CredentialStore -UseCertStore -Force
$Path = Get-DefaultCredentialStorePath
$StoreHome = Split-Path -Path $Path -Parent
$CertFile = Join-Path -Path $StoreHome -ChildPath 'PSCredentialStore.pfx'
$Cert = Get-PfxCertificate -FilePath $CertFile
$myStore = [System.Security.Cryptography.X509Certificates.X509Store]::new('My')
$myStore.Open("ReadWrite")
$myStore.Add($Cert)
$MyStore.Close()
$UserName = 'testuser'
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
[PSCredential]::new($UserName, $Password) | New-CredentialStoreItem -RemoteHost 'foobarcerts'
$writtenItem = Get-CredentialStoreItem -RemoteHost 'foobarcerts'
$writtenItem.UserName | Should -Be "testuser"
$writtenItem.GetNetworkCredential().Password | Should -Be 'mypasswd'
}
}
}

View File

@ -0,0 +1,10 @@
Describe "Test-CSPfxCertificate" {
Context "Basic Tests" {
It "Should not Throw" {
{ Test-CSPfxCertificate -Thumbprint '12345' -StoreName My -StoreLocation CurrentUser } | Should -Not -Throw
}
It "Should return false" {
Test-CSPfxCertificate -Thumbprint '12345' -StoreName My -StoreLocation CurrentUser | Should -Be $false
}
}
}

View File

@ -0,0 +1,49 @@
Describe "Get-DefaultCredentialStorePath" {
Context "Basic syntax test" {
It "Test1: Should not throw" {
{ Get-DefaultCredentialStorePath } | Should -Not -Throw
}
}
Context "Private Type" {
It "Should return correct paths" {
$Path = Get-DefaultCredentialStorePath
#Write-Verbose -Message ('Delivered path is: {0}' -f $Path) -Verbose
if ($Env:APPVEYOR) {
$PathRef = Join-Path -Path $Env:APPDATA -ChildPath 'CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($ENV:TRAVIS) {
if ($IsLinux) {
$PathRef = Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($IsMacOS) {
$PathRef = Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
$Path | Should -Be $PathRef
}
}
}
}
Context "Shared Type" {
It "Should return correct paths" {
$Path = Get-DefaultCredentialStorePath -Shared
#Write-Verbose -Message ('Delivered path is: {0}' -f $Path) -Verbose
if ($Env:APPVEYOR) {
$PathRef = Join-Path -Path $env:ProgramData -ChildPath 'PSCredentialStore/CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($ENV:TRAVIS) {
if ($IsLinux) {
$PathRef = Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($IsMacOS) {
$PathRef = Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
$Path | Should -Be $PathRef
}
}
}
}
}

View File

@ -0,0 +1,7 @@
Describe "Get-ModuleBase" {
Context "Basic syntax check" {
It "Test1: Should not throw" {
{ Get-ModuleBase } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,13 @@
Describe "Get-RandomKey" {
Context "Basic input tests" {
It "Test1: Should not throw " {
{Get-RandomAESKey} | Should -Not -Throw
}
}
Context "Basic syntax check" {
It "Test2: Should return a key with a length of 32 bytes" {
$Key = Get-RandomAESKey
$Key.length | Should -Be 32
}
}
}

View File

@ -0,0 +1,27 @@
Describe "Get-TempDir" {
Context "Basic tests" {
It "Should not throw" {
{Get-TempDir} | Should -Not -Throw
}
It "Should return the correct os tmp path" {
$Path = Get-TempDir
if ($ENV:TRAVIS) {
if ($IsLinux) {
$RefPath = (Resolve-Path -Path '/tmp/').Path
$Path | Should -Be $RefPath
}
if ($IsMacOS) {
$RefPath = (Resolve-Path -Path '/tmp/').Path
$Path | Should -Be $RefPath
}
}
if ($Env:APPVEYOR) {
if (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
$RefPath = (Resolve-Path -Path $env:TEMP).Path
$Path | Should -Be $RefPath
}
}
}
}
}

View File

@ -0,0 +1,35 @@
Describe "Resolve-Dependency" {
Context "Basic syntax check" {
Mock Get-ModuleBase {return (Join-Path -Path $PWD -ChildPath '/resources')}
Mock Test-Module {return $true}
It "Test1: Should not throw" {
{ Resolve-Dependency -Name 'foobar2000' } | Should -Not -Throw
}
It "Test2: Output type should be bool" {
Resolve-Dependency -Name 'foobar2000' | Should -BeOfType bool
}
}
Context "Enforce Error" {
# Return incorrect module base to enforce there is no config file.
Mock Get-ModuleBase {
if ($IsWindows) {return "C:\"}
elseif ($isLinux) {return "/"}
}
It "Missing dependency file should not cause an error" {
{ Resolve-Dependency -Name 'awesome'} | Should -Not -Throw
}
It "Missing dependency file should return true" {
Resolve-Dependency -Name 'awesome' | Should -Be $true
}
}
Context "Testing input variations" {
Mock Get-ModuleBase {return (Join-Path -Path $PWD -ChildPath '/resources')}
It "Should return true if all given dependencies exist" {
Resolve-Dependency -Name 'Existing' | Should -Be $true
}
It "Mixed results should return false" {
Resolve-Dependency -Name 'PSGetMixed' | Should -Be $false
}
}
}

View File

@ -0,0 +1,26 @@
Describe "Test-ModuleName" {
Context "Basic input tests" {
It "Testing standard module should not throw" {
{ Test-Module -Name 'PowerShellGet' } | Should -Not -Throw
}
It "Existing module should return true" {
Test-Module -Name 'PowerShellGet' | Should -Be $true
}
}
Context "Working with modules" {
It "Loading first module should not throw " {
$Mod = Get-Module -ListAvailable | Select-Object -First 1
{ Test-Module -Name $Mod.Name } | Should -Not -Throw
}
It "Loading first module should return true" {
$Snap = Get-Module -ListAvailable | Select-Object -First 1
Test-Module -Name $Snap.Name | Should -Be $true
}
It "Not existing module should return false" {
Test-Module -Name 'foobar2000' | Should -Be $false
}
It "StopifFails switch should thrown an error" {
{Test-Module -Name 'foobar2000' -StopIfFails }| Should -Throw
}
}
}

View File

@ -1,37 +0,0 @@
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# $RepoRoot = (Get-Item -Path $here).Parent.Parent.FullName
$RepoRoot = (Get-GitDirectory).replace('\.git', '')
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude ".\tests\" -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
# load additional functions defined in the repository. Replace the expression <FunctionName>.
. (Get-ChildItem -Path $RepoRoot -Filter "Test-CredentialStore.ps1" -Recurse).FullName
#endregion HEADER
Describe "Get-CredentialStore" {
Context "Basic logic tests" {
$TestCredentialStore = Resolve-Path -Path ("{0}\resources\cs\CredentialStore.json" -f $RepoRoot)
It "Test1: Read CS without params" {
If (Test-Path -Path ("{0}\CredentialStore.json" -f $env:APPDATA)) {
{Get-CredentialStore} | Should Not Throw
}
Else {
Write-Warning "Default private Credential Store not found. Skipping..."
}
}
It "Test2: Read Credential Store with testing data" {
{Get-CredentialStore -Path $TestCredentialStore} | Should Not Throw
}
}
}

Some files were not shown because too many files have changed in this diff Show More