Compare commits

...

49 Commits

Author SHA1 Message Date
OCram85 f2b7910b15 Prepare release v1.1.1 (#78)
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
#### 📖 Summary

- updates changelog

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #78
2022-10-10 10:24:52 +02:00
OCram85 0b5c9823e0 Adds changelog config for gitea changelog cli tool (#77)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- adds initial default config for changelog generation

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [ ] Tested via Drone.io pipeline
- [x] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #77
2022-10-10 10:10:18 +02:00
pinguinfuss 42fdb0a373 Fix Set-CredentialStoreItem (#76)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- Fix Set-CredentialStoreItem. Currently it doesn't warn if the user is trying to update a CredentialStoreItem, that does not exist.
- Also add a bit of documentation and UnitTests.
- Fix the quotation of Test-CredentialStoreItem.

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <ocram85@noreply.local>
Reviewed-on: #76
Reviewed-by: OCram85 <ocram85@noreply.local>
Co-authored-by: pinguinfuss <christian@heimdaheim.de>
Co-committed-by: pinguinfuss <christian@heimdaheim.de>
2022-10-10 10:05:08 +02:00
pinguinfuss 2bd250971b Fix optional module dependencies (#75)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- Fix the optional dependencies.
  - DataONTAP was never a PSGallery module, and we have to custom build that.
  - NetApp finally submitted NetApp.ONTAP into PSGallery, so we can depend on that.
- Updates UCS- and VMware-modules.

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [ ] Tested via Drone.io pipeline
- [ ] Custom test
- [x] No test plan

##### Details / Justification

Sadly, you have to run it. The module loader does not have a unit test.

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <ocram85@noreply.local>
Reviewed-on: #75
Reviewed-by: OCram85 <ocram85@noreply.local>
Co-authored-by: pinguinfuss <christian@heimdaheim.de>
Co-committed-by: pinguinfuss <christian@heimdaheim.de>
2022-10-10 10:00:42 +02:00
OCram85 ac6a9d8202 prepare release 1.1.0 (#74)
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
#### 📖 Summary

- updates changelog

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #74
2022-09-21 09:39:56 +02:00
OCram85 3d4f53ddc7 adds pinguinfuss contributed fix (#73)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- redo PR from @pinguinfuss
  - fix error message
  - fix string quotation

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

- just redo #72.
  - there was an issue caused by git config `core.autocrl` displaying / diffin the wrong line ending sequence

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #73
2022-09-20 15:01:05 +02:00
OCram85 6fce8d6a8c Updates libressl files (#71)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- adds missing `vendor` files into build package.
- adds missing `openssl.conf` in build package.
- updates libressl / openssl to v3.5.3

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

-  See `v1.1.0-dev9` build
  - https://gitea.ocram85.com/OCram85/PSCredentialStore/releases/tag/v1.1.0-dev9
Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #71
2022-09-20 11:58:29 +02:00
OCram85 ddb85d907f addChangelog (#70)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- adds CHANGELOG.md via DroneHelper

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #70
2022-07-28 15:15:52 +02:00
OCram85 5bdb383627 updates Readme (#69)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- fix typos
- Updates several sections

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #69
2022-07-28 10:41:46 +02:00
OCram85 a95ba31e40 remove optional depenency helper (#68)
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
#### 📖 Summary

- removed optional dependency helper. Moved optional deps into `ExternalModuleDependencies` field.

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #68
2022-07-26 11:33:10 +02:00
OCram85 1e7dd78c2b adds CiscoUCSCentral connection type (#67)
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build was killed Details
#### 📖 Summary

- adds CiscoUCSCentrall connection type in `Connect-To` and `Disconnect-From`

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #67
2022-07-19 14:29:25 +02:00
OCram85 b76668c1e7 fix Test-CredentialStoreItem return (#66)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- `Test-CredentialStoreItem` now returns `$false` and not a terminating error if store doesn't exists.
- Updates platyPS generated docs

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

- fixes #50

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #66
2022-07-19 11:46:21 +02:00
OCram85 ae62cccfaa switch to GNU AGPLv3 license (#64)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- Switch to GNU AGPLv3 license

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #64
2022-07-15 11:34:00 +02:00
OCram85 a66e8249db adds community contribution for CiscoUCS connection fix (#63)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- relates to #53

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #63
2022-07-15 11:25:11 +02:00
OCram85 3d90d912ee fix lint (PSScriptAnalyzer) issues (#62)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

<!-- Provide a summary of your changes. Describe the why and not how. -->

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #62
2022-07-15 10:59:56 +02:00
OCram85 d0b7e53c80 adds DroneHelper (#61)
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/pr Build is failing Details
#### 📖 Summary

- adds DroneHelper for build pipeline

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

- FileLint / Lint & Pester issues will be fixed in next PR

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #61
2022-07-15 08:28:21 +02:00
OCram85 d4b00a5308 Migrates to Pester5+ tests (#59)
continuous-integration/drone/push Build was killed Details
#### 📖 Summary

- update Pester tests to Pester5+ compatiple layout
- switch to dotnet base imaged
  - dotnet binary required for publishung powershell modules (Publish-Module)

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #59
2022-07-14 13:37:12 +02:00
OCram85 e3404666d4 update references (#60)
continuous-integration/drone/push Build is passing Details
#### 📖 Summary

- Replace all github refs with gitea url

#### 📑 Test Plan

> 💡 Select your test plan for the code changes.

- [x] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan

##### Details / Justification

<!-- Add your test details or justification for missing tests here. -->

#### 📚 Additional Notes

<!-- A place for additional detail notes. -->

Co-authored-by: OCram85 <marco.blessing@googlemail.com>
Reviewed-on: #60
2022-07-13 08:34:31 +02:00
OCram85 88743e9ffd
fix pester verbosity config (#58)
continuous-integration/drone Build was killed Details
* fix pester verbosity config

* debug ScriptAnalayzer output
2022-06-28 09:52:29 +02:00
OCram85 c31ee791bb
Update issue templates (#57)
* Update issue templates

* debug PSScriptAnalyzer
2022-06-28 09:41:53 +02:00
OCram85 c45490aefe
Update issue templates (#56) 2022-06-28 09:21:01 +02:00
OCram85 4abfec5725
adds PR template (#55) 2022-06-28 09:12:34 +02:00
OCram85 7708df9b66
Update pwsh style to latest community standards (#52)
* update pwsh style in store files

* update pwsh style in item files

* update pwsh style in connection files

* update pwsh style in certificate files

* update pwsh style in private files

* update pwsh style in drone helper

* update meta

* fix pwsh style

* fix output type

* fix typo in OutputType

* update appveyor build mode

* debugging build mode

* wip

* test windows pipeline

* fix typo

* simplify drone setup

* update readme

* remove deprecated cicd setup

* update pwsh style
2022-06-28 08:56:33 +02:00
OCram85 739c8cb9b0
stop raising build error on lint warnings for now (#49) 2020-10-02 16:06:22 +02:00
OCram85 5983c760b5 disable error on lint warnings 2020-10-02 15:52:59 +02:00
OCram85 045adbf647
Modernize Build Pipeline (#48) 2020-10-02 15:48:58 +02:00
OCram85 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
OCram85 d0a6457d37
Adds Social Logo (#46)
* add social logo
* add social logo in Readme
2019-05-10 10:12:26 +02:00
OCram85 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
OCram85 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
OCram85 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
OCram85 dbf53b7cb0
publish 0.5.xxx-alpha1 release 2019-01-16 13:18:27 +01:00
OCram85 09548fca0a
add debug output (#36) 2019-01-16 13:02:51 +01:00
OCram85 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
OCram85 ab13962f6e
Fix FTP Connection Error (#29)
* fixes #27
* fix var name typo
* bump version
2018-03-26 13:01:34 +02:00
OCram85 680f37c00e fixed another var name typo 2018-03-21 15:30:14 +01:00
OCram85 1773f1fc06 fixes #26 2018-03-21 15:18:18 +01:00
OCram85 c0b13052b3
Enables pipeline input for -Credential parameter (#25) 2018-03-21 14:32:32 +01:00
OCram85 8d55f2d6fd
disable AppVeyor builds for specific branches (fixes #23) 2018-03-21 12:52:59 +01:00
OCram85 ce823d4564
Increase code coverage (#22) 2018-03-21 12:16:09 +01:00
OCram85 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
OCram85 691255957c
Remove old Write-Message2 function (#13) 2018-03-02 13:43:06 +01:00
OCram85 cb11209702
Publish 0.2.0 (#12) 2017-12-22 08:10:37 +01:00
OCram85 6659c2b317
update badges (#11) 2017-11-15 10:17:23 +01:00
OCram85 599232ecec Implements CisServer connection handling (#10)
### fixes #8 

- gh deployment for dev branch removed
  - duplicate deployment.
  - see appveyor artifacts.
- installation of dependencies moved to ps function
- modularize PSGallery Deployment branch
- update platPS docs
- enable private build
- Implements ConnectionType CisServer (#9)
2017-10-23 10:53:52 +02:00
OCram85 855cb920c8 Set theme jekyll-theme-midnight 2017-10-23 08:11:25 +02:00
OCram85 8c92028b09 fix typos (#7)
* disable auto deployment for upcomming typo fixes
* fix typos
2017-10-16 19:47:19 +02:00
OCram85 b63fd6780a Set theme jekyll-theme-modernist 2017-09-28 11:10:55 +02:00
OCram85 dbe5319537 Adds markdown help pages in docs folder
* adds docs folder (#5)
  * fist module description
  * adds cmdlet markdown help
  * adds meta pages
2017-09-28 11:08:41 +02:00
109 changed files with 7286 additions and 1721 deletions

32
.changelog.yml Normal file
View File

@ -0,0 +1,32 @@
# The full repository name
repo: OCram85/PSCredentialStore
# Service type (gitea or github)
service: gitea
# Base URL for Gitea instance if using gitea service type (optional)
# Default: https://gitea.com
base-url: https://gitea.ocram85.com
# Changelog groups and which labeled PRs to add to each group
groups:
- name: ✨ FEATURES
labels:
- feature
- name: 📦 META
labels:
- meta
- name: 🐛 BUGFIXES
labels:
- bug
- name: 🛠️ ENHANCEMENTS
labels:
- enhancement
- name: 📚 DOCS
labels:
- docs
- name: 🔖 MISC
default: true
# regex indicating which labels to skip for the changelog
skip-labels: skip-changelog|backport\/.+

151
.drone.yml Normal file
View File

@ -0,0 +1,151 @@
---
kind: pipeline
type: docker
name: "Build Pipeline"
trigger:
branch:
exclude:
- droneDocs/*
steps:
- name: "Pwsh FileLinter"
image: mcr.microsoft.com/dotnet/sdk:6.0-focal
failure: ignore
environment:
EXCLUDE: "(.exe|.dll|.ico|.gitkeep|Vendor|.Tests.ps1)"
commands:
- |
apt-get update
apt-get install -y file
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module 'DroneHelper' -ErrorAction 'Stop';
Invoke-FileLinter
}"
- name: "ScriptAnalyzer"
image: mcr.microsoft.com/dotnet/sdk:6.0-focal
failure: ignore
commands:
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module -Name 'DroneHelper' -ErrorAction 'Stop';
Install-ModuleDependency;
Invoke-Linter
}"
- name: "Pester"
image: mcr.microsoft.com/dotnet/sdk:6.0-focal
failure: ignore
commands:
- |
apt-get update
apt-get install -y file
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module -Name 'DroneHelper' -ErrorAction 'Stop';
Install-ModuleDependency;
Invoke-UnitTest -Verbosity 'Detailed' -ExcludeTag 'Integration'
}"
- name: "PRComment"
image: mcr.microsoft.com/dotnet/sdk:6.0-focal
failure: ignore
environment:
GITEA_TOKEN:
from_secret: GITEA_TOKEN
CUSTOM_PIPELINE_STATE: true
LOG_FILES: "build/*.log"
commands:
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module -Name 'DroneHelper' -ErrorAction 'Stop';
Send-PRComment
}"
when:
event:
include:
- pull_request
depends_on:
- "Pwsh FileLinter"
- "ScriptAnalyzer"
- "Pester"
- name: "buildState"
image: mcr.microsoft.com/dotnet/sdk:6.0-focal
commands:
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module -Name 'DroneHelper' -ErrorAction 'Stop';
Install-ModuleDependency;
Invoke-BuildState
}"
depends_on:
- "PRComment"
---
kind: pipeline
type: docker
name: "Publish Pipeline"
depends_on:
- "Build Pipeline"
trigger:
event:
- tag
steps:
- name: BuildArtifacts
image: mcr.microsoft.com/dotnet/sdk:6.0-focal
#failure: ignore
commands:
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module -Name 'DroneHelper' -ErrorAction 'Stop';
Install-ModuleDependency;
Update-ModuleMeta -Verbose
}"
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module -Name 'DroneHelper' -ErrorAction 'Stop';
Install-ModuleDependency;
New-BuildPackage -Verbose -AdditionalPath @('./src/Vendor', './src/openssl.conf')
}"
- name: GiteaRelease
image: plugins/gitea-release
settings:
api_key:
from_secret: GITEA_TOKEN
base_url: https://gitea.ocram85.com
files:
- "bin/${DRONE_REPO_NAME}.zip"
- "bin/PSModule.zip"
title: "${DRONE_TAG}"
note: CHANGELOG.md
- name: "PublishModule"
image: mcr.microsoft.com/dotnet/sdk:6.0-focal
#failure: ignore
environment:
NuGetToken:
from_secret: PSGallery
commands:
- |
pwsh -NonInteractive -c "& {
Install-Module -Name 'DroneHelper' -Repository 'PSGallery' -ErrorAction 'Stop' -AllowPrerelease -Force;
Import-Module -Name 'DroneHelper' -ErrorAction 'Stop';
Install-ModuleDependency;
Invoke-Publish -Verbose
}"

31
.editorconfig Normal file
View File

@ -0,0 +1,31 @@
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{.gitattributes,.gitignore,.gitkeep}]
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true

25
.gitattributes vendored Normal file
View File

@ -0,0 +1,25 @@
# images
*.jpg binary
*.jpeg binary
*.bmp binary
*.tiff binary
*.png binary
*.svg binary
*.ico binary
# binary files
*.exe binary
*.dll binary
# PowerShell specific
*.ps1 working-tree-encoding=UTF-8
*.psm1 working-tree-encoding=UTF-8
*.psd1 working-tree-encoding=UTF-8
# set markdown to lf for online editing
*.md working-tree-encoding=UTF-8
# Vendor resources config
src/Vendor/libressl255/* filter=lfs diff=lfs merge=lfs -text
src/Vendor/libressl/* filter=lfs diff=lfs merge=lfs -text
*.pfx filter=lfs diff=lfs merge=lfs -text

11
.gitea/ISSUE_TEMPLATE.md Normal file
View File

@ -0,0 +1,11 @@
----
name: "Default"
about: "Use this template if nothing seems to work."
title: ":question: "
labels:
- question
----
#### :grey_question: Simply ask your question here: :grey_question:
<!-- Take your time an think about your problem.... -->

View File

@ -0,0 +1,48 @@
----
name: "Bug"
about: "This template is used to report bugs!"
title: ":lady_beetle: "
labels:
- bug
----
<!--
This bug report is ony for content provided in this repository!
- Make sure you're able to reproduce the error in the lastest version of this package.
- Search of already existing issues.
- Refer to the known issues and FAQ section.
-->
#### :bomb: Steps to reproduce
```bash
```
#### :rocket: Expected behavior
```bash
```
#### :boom: Actual behavior
```bash
```
#### :notebook: Environment data
<!-- You can add additional environment data here--->
```bash
```
#### :framed_picture: Screenshots
<!-- Paste your screenshots here. -->
#### :bookmark: Refs
<!-- A place for addtional references to othe issues and PRs -->

View File

@ -0,0 +1,24 @@
----
name: "Enhancement"
about: "Wite about new features."
title: ":flying_saucer: "
labels:
- enhancement
----
<!--
This issue template is used to describe whished features.
-->
#### :satellite: Suggestion
#### :artificial_satellite: Implementation ideas
#### :framed_picture: Mock-up Images
#### :bookmark: Refs.

View File

@ -0,0 +1,19 @@
#### :book: Summary
<!-- Provide a summary of your changes. Describe the why and not how. -->
#### :bookmark_tabs: Test Plan
> :bulb: Select your test plan for the code changes.
- [ ] Tested via Drone.io pipeline
- [ ] Custom test
- [ ] No test plan
##### Details / Justification
<!-- Add your test details or justification for missing tests here. -->
#### :books: Additional Notes
<!-- A place for additional detail notes. -->

24
.gitignore vendored
View File

@ -1,3 +1,21 @@
# Don't local track test builds
bin/PSCredentialStore.zip
bin/PSCredentialStore/*
# Don't local track test builds
bin/PSCredentialStore.zip
bin/PSCredentialStore/*
# Basic ignore patterns
*.log
*.secret
# data dir related prod files
data/*.csv
# Ignore templ build artifacts
/bin/*
!bin/.gitkeep
# Ignore Unit Test result files
coverage.xml
testResults.xml
# Optional build state file
STATE.xml

62
.vscode/cSpell.json vendored
View File

@ -1,40 +1,22 @@
// cSpell Settings
{
// Version of the setting file. Always 0.1
"version": "0.1",
// language - current active spelling language
"language": "en",
// words - list of words to be always considered correct
"words": [
"Cmdlet",
"Cmdlets",
"GUID",
"Hashtable",
"Httpclient",
"Multipart",
"NTFS",
"Params",
"Ponduit",
"Repo",
"Veyor",
"appveyor",
"callsign",
"choco",
"chocolatey",
"codecoverage",
"creds",
"formdata",
"googlemail",
"notlike",
"notmatch",
"powershellgallery",
"testresults",
"wildcards"
],
// flagWords - list of words to be always considered incorrect
// This is useful for offensive words and common spelling errors.
// For example "hte" should be "the"
"flagWords": [
"hte"
]
}
// cSpell Settings
{
// Version of the setting file. Always 0.1
"version": "0.2",
// language - current active spelling language
"language": "en,de,de-DE",
// words - list of words to be always considered correct
"words": [],
// flagWords - list of words to be always considered incorrect
// This is useful for offensive words and common spelling errors.
// For example "hte" should be "the"
"flagWords": [],
"dictionaryDefinitions": [
{
"name": "default",
"path": "./dictionaries/default.txt"
}
],
"dictionaries": [
"default"
]
}

13
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,13 @@
{
"recommendations": [
"streetsidesoftware.code-spell-checker",
"streetsidesoftware.code-spell-checker-german",
"hediet.vscode-drawio",
"editorconfig.editorconfig",
"eamodio.gitlens",
"vscode-icons-team.vscode-icons",
"redhat.vscode-xml",
"redhat.vscode-yaml",
"ryanluker.vscode-coverage-gutters"
]
}

96
.vscode/launch.json vendored
View File

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

31
.vscode/pwsh.code-snippets vendored Normal file
View File

@ -0,0 +1,31 @@
{
// Place your PowerShell-Module workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
// Example:
// "Print to console": {
// "scope": "javascript,typescript",
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
// PSScriptAnalyzder Rule Suppression
"Rule Suppression": {
"scope": "powershell",
"prefix": "[Diag",
"description": "Suppresses Scriptanalyzer Rules",
"body": [
"[Diagnostics.CodeAnalysis.SuppressMessageAttribute(",
" '${1|PSProvideCommentHelp,PSAvoidLongLines,PSAvoidUsingWriteHost,PSUseShouldProcessForStateChangingFunctions|}',",
" '',",
" Justification = '${justification}'",
")]"
]
}
}

102
.vscode/settings.json vendored
View File

@ -1,50 +1,52 @@
// Place your settings in this file to overwrite default and user settings.
{
// Set basic file related options:
"files.encoding": "utf8",
"files.eol": "\r\n",
"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
// Formation and editor options
"editor.renderWhitespace": "boundary",
"editor.formatOnSave": true,
"editor.formatOnType": true,
"editor.rulers": [
116
],
// powershell general
"powershell.startAutomatically": true,
"powershell.useX86Host": false,
"powershell.enableProfileLoading": true,
"powershell.scriptAnalysis.enable": true,
// powershell code Formatting
"powershell.codeFormatting.openBraceOnSameLine": true,
"powershell.codeFormatting.newLineAfterOpenBrace": true,
"powershell.codeFormatting.newLineAfterCloseBrace": true,
"powershell.codeFormatting.whitespaceBeforeOpenBrace": true,
"powershell.codeFormatting.whitespaceBeforeOpenParen": true,
"powershell.codeFormatting.whitespaceAroundOperator": true,
"powershell.codeFormatting.whitespaceAfterSeparator": true,
"powershell.codeFormatting.ignoreOneLineBlock": true,
"powershell.codeFormatting.alignPropertyValuePairs": false,
// cspell spellchecker options
"cSpell.enabledLanguageIds": [
"c",
"cpp",
"csharp",
"go",
"javascript",
"javascriptreact",
"json",
"latex",
"markdown",
"php",
"plaintext",
"powershell",
"python",
"text",
"typescript",
"typescriptreact",
"yml"
]
}
{
"files.encoding": "utf8",
"files.eol": "auto",
"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
"editor.renderWhitespace": "boundary",
"editor.formatOnSave": true,
"editor.formatOnType": true,
"editor.rulers": [
116
],
"cSpell.enabled": true,
"cSpell.enabledLanguageIds": [
"c",
"cpp",
"csharp",
"go",
"javascript",
"javascriptreact",
"json",
"latex",
"markdown",
"php",
"plaintext",
"powershell",
"python",
"text",
"typescript",
"typescriptreact",
"yaml",
"yml"
],
"cSpell.language": "en,de,de-DE",
// powershell general
"powershell.startAutomatically": true,
"powershell.useX86Host": false,
"powershell.enableProfileLoading": true,
"powershell.scriptAnalysis.enable": true,
// powershell code Formatting
"powershell.codeFormatting.openBraceOnSameLine": true,
"powershell.codeFormatting.newLineAfterOpenBrace": true,
"powershell.codeFormatting.newLineAfterCloseBrace": true,
"powershell.codeFormatting.whitespaceBeforeOpenBrace": true,
"powershell.codeFormatting.whitespaceBeforeOpenParen": true,
"powershell.codeFormatting.whitespaceAroundOperator": true,
"powershell.codeFormatting.whitespaceAfterSeparator": true,
"powershell.codeFormatting.ignoreOneLineBlock": true,
"powershell.codeFormatting.alignPropertyValuePairs": true,
"powershell.scriptAnalysis.settingsPath": "./tools/PSScriptAnalyzerSettings.psd1",
"coverage-gutters.showGutterCoverage": false,
"coverage-gutters.showLineCoverage": true
}

151
.vscode/tasks.json vendored
View File

@ -1,56 +1,121 @@
// A task runner that invokes Pester to run all Pester tests under the
// current workspace folder.
// NOTE: This Test task runner requires an updated version of Pester (>=4.0.3)
// in order for the problemMatcher to find failed test information (message, line, file).
// If you don't have that version, you can update Pester from the PowerShell Gallery
// with this command:
//
// PS C:\> Update-Module Pester
//
// If that gives an error like:
// "Module 'Pester' was not installed by using Install-Module, so it cannot be updated."
// then execute:
//
// PS C:\> Install-Module Pester -Scope CurrentUser -Force
//
// NOTE: The Clean, Build and Publish tasks require PSake. PSake can be installed
// from the PowerShell Gallery with this command:
//
// PS C:\> Install-Module PSake -Scope CurrentUser -Force
//
// Available variables which can be used inside of strings:
// ${workspaceFolder} the path of the workspace folder that contains the tasks.json file
// ${workspaceFolderBasename} the name of the workspace folder that contains the tasks.json file without any slashes (/)
// ${file} the current opened file
// ${relativeFile} the current opened file relative to the workspace folder containing the file
// ${fileBasename} the current opened file's basename
// ${fileBasenameNoExtension} the current opened file's basename without the extension
// ${fileDirname} the current opened file's dirname
// ${fileExtname} the current opened file's extension
// ${cwd} the task runner's current working directory on startup
// ${lineNumber} the current selected line number in the active file
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
// Start PowerShell
"windows": {
"command": "${env:windir}/System32/WindowsPowerShell/v1.0/powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass"
]
},
//"windows": {
// "options": {
// "shell": {
// // switch back to windows powershell 5.1
// // "executable": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
// "executable": "pwsh.exe",
// "args": [
// "-NoProfile",
// "-ExecutionPolicy",
// "Bypass",
// "-Command"
// ]
// }
// }
//},
"linux": {
"command": "/usr/bin/powershell",
"args": [
"-NoProfile"
]
},
"osx": {
"command": "/usr/local/bin/powershell",
"args": [
"-NoProfile"
]
"options": {
"shell": {
"executable": "/usr/bin/pwsh",
"args": [
"-NoProfile",
"-Command"
]
}
}
},
//"osx": {
// "options": {
// "shell": {
// "executable": "/usr/local/bin/pwsh",
// "args": [
// "-NoProfile",
// "-Command"
// ]
// }
// }
//},
"tasks": [
{
"taskName": "Test",
"suppressTaskName": true,
"args": [
"Write-Host 'Invoking Pester...'; $ProgressPreference = 'SilentlyContinue'; Invoke-Pester -Script '.\\tests\\*' -EnableExit $flase -PesterOption @{IncludeVSCodeMarker=$true};",
"Invoke-Command { Write-Host 'Completed Test task in task runner.' }"
"label": "DroneIO: Invoke-Linter",
"type": "shell",
"command": [
"Import-Module ./tools/DroneIO.psm1;",
"Invoke-Linterq | Format-Table -AutoSize"
],
"problemMatcher": "$pester",
"group": {
"kind": "test",
"isDefault": true
}
"group": "test",
"problemMatcher": [
"$pester"
]
},
{
"taskName": "DebugBuild",
"suppressTaskName": true,
"args": [
"Write-Host 'Invoking Build...';",
"Write-Host -Object 'Test previous builds.' -ForegroundColor Blue;",
"If (Test-Path -Path '.\\bin\\PSCredentialStore.zip') { Remove-Item -Path '.\\bin\\PSCredentialStore.zip' -Verbose};",
"Copy-Item -Path '.\\src\\' -Destination '.\\bin\\PSCredentialStore' -Recurse -Verbose -Force;",
"Compress-Archive -Path '.\\src\\*' -DestinationPath '.\\bin\\PSCredentialStore.zip' -Update -Verbose;"
"label": "DroneIO: Invoke-UnitTest",
"type": "shell",
"command": [
"Remove-Item ./coverage.xml -ErrorAction 'SilentlyContinue';",
"Remove-Item ./testResults.xml -ErrorAction 'SilentlyContinue';",
"Import-Module ./tools/DroneIO.psm1;",
"Invoke-UnitTest -CoverageFormat 'CoverageGutters' -Verbosity 'Diagnostic'"
],
"group": {
"kind": "build",
"isDefault": true
}
"group": "test",
"problemMatcher": [
"$pester"
]
},
{
"label": "Add dictionary item",
"type": "shell",
"command": [
"$DefaultFile = Get-ChildItem -Path './.vscode/dictionaries/default.txt';",
"$Content = Get-Content -Path $DefaultFile;",
"$Content += '${input:DictionaryItem}';",
"$Content = $Content | Sort-Object -Unique;",
"Set-Content -Value $Content -Path $DefaultFile"
],
"group": "none",
"problemMatcher": [
"$pester"
]
}
],
"inputs": [
{
"id": "DictionaryItem",
"type": "promptString",
"description": "Input for dictionary file default.txt"
}
]
}

41
CHANGELOG.md Normal file
View File

@ -0,0 +1,41 @@
# Changelog
<!-- insertMark -->
## [v1.1.1](https://gitea.ocram85.com/OCram85/PSCredentialStore/releases/tag/v1.1.1) - 2022-10-10
* 📦 META
* Adds changelog config for gitea changelog cli tool (#77)
* 🐛 BUGFIXES
* Fix Set-CredentialStoreItem (#76)
* Fix optional module dependencies (#75)
### Contributors
* [@OCram85](https://gitea.ocram85.com/OCram85)
* [@pinguinfuss](https://gitea.ocram85.com/pinguinfuss)
## `v1.1.0`
- (3d4f53d) adds pinguinfuss contributed fix (#73)
- (6fce8d6) Updates libressl files (#71)
- (ddb85d9) addChangelog (#70)
- (5bdb383) updates Readme (#69)
- (a95ba31) remove optional depenency helper (#68)
- (1e7dd78) adds CiscoUCSCentral connection type (#67)
- (b76668c) fix Test-CredentialStoreItem return (#66)
- (ae62ccc) switch to GNU AGPLv3 license (#64)
- (a66e824) adds community contribution for CiscoUCS connection fix (#63)
- (3d90d91) fix lint (PSScriptAnalyzer) issues (#62)
- (d0b7e53) adds DroneHelper (#61)
- (d4b00a5) Migrates to Pester5+ tests (#59)
- (e340466) update references (#60)
- (88743e9) fix pester verbosity config (#58)
- (c31ee79) Update issue templates (#57)
- (c45490a) Update issue templates (#56)
- (4abfec5) adds PR template (#55)
- (7708df9) Update pwsh style to latest community standards (#52)
## `v1.0.542`
- 🧙 pre migrated Gitea version

248
LICENSE
View File

@ -1,21 +1,235 @@
MIT License
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2017 Marco Blessing
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
Preamble
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.

284
README.md
View File

@ -1,84 +1,200 @@
| AppVeyor Overall | AppVeyor Master | AppVeyor Dev | Coveralls.io | Download |
| :--------------: | :-------------: | :----------: | :-----------: | :--------:|
| [![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)
General
=======
The PSCredentialStore is an simple credential manager for PSCredentials. It stores multiple credential objects in a
simple json file. You can choose between a private and shared 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
script 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
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.
Installation
============
PowerShellGallery.com (Recommended Way)
---------------------------------------
* Make sure you use PowerShell 4.0 or higher with `$PSVersionTable`.
* Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore`
* Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore`
Manual Way
----------
* Take a look at the [Latest Release](https://github.com/OCram85/PSCredentialStore/releases/latest) page.
* Download the `PSCredentialStore.zip`.
* Unpack the Zip and put it in your Powershell Module path.
* Don't forget to change the NTFS permission flag in the context menu.
* Start with `Import-Module PSCredentialStore`
Quick Start
-----------
**1.** First we need a blank CredentialStore. 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.
```powershell
# Private Credential Store
New-CredentialStore
# Shared Credential Store
New-CredentialStore -Shared
#Shared CredentialStore in custom Location
New-CredentialStore -Shared -Path 'C:\CredentialStore.json'
```
**2.** Now you can manage your CredentialStoreItems:
```powershell
# This will prompt for credentials and stores it in a private store
New-CredentialStoreItem -RemoteHost 'dc01.myside.local' -Identifier 'AD'
# You can now use it in other scripts like this:
$DCCreds = Get-CredentialStoreItem -RemoteHost 'dc01.myside.local' -Identifier 'AD'
Invoke-Command -ComputerName 'dc01.myside.local' -Credential $DCCreds -ScripBlock {Get-Process}
```
The CredentialStore contains also a simple function to establish a connection with several systems or protocols.
If you have already installed the underlying framework your can connect to:
* **CiscoUcs** - Establish a connection to a Cisco UCS fabric interconnect.
* Required Modules: [`Cisco.UCS.Core`, `Cisco.UCSManager`](https://software.cisco.com/download/release.html?i=!y&mdfid=286305108&softwareid=284574017&release=2.1.1)
* **FTP** - Establish a connection to a FTP host.
* Required Modules: [`WinSCP`](https://www.powershellgallery.com/packages/WinSCP)
* **NetAppFAS** - Establish a connection to a NetApp Clustered ONTAP filer.
* Required Modules: [`DataONTAP`](http://mysupport.netapp.com/tools/info/ECMLP2310788I.html?productID=61926)
* **VMware** - Establish a connection to a VMware vCenter or ESXi host.
* Required Modules: [`VMware.VimAutomation.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI)
Here are some basic examples:
```powershell
Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs
Connect-To -RemoteHost "ftp.myside.local" -Type FTP
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
Connect-To -RemoteHost "esx01.myside.local" -Type VMware
```
<p align="right">
<img src="http://forthebadge.com/images/badges/built-with-love.svg">
<img src="http://forthebadge.com/images/badges/for-you.svg">
</p>
<p align="center">
<a href="https://gitea.ocram85.com/OCram85/PSCredentialStore/">
<img
src="https://gitea.ocram85.com/OCram85/PSCredentialStore/raw/branch/master/assets/social-logo.png"
alt="PSCredentialStore"
>
</a>
</p>
<h1 align="center">
PSCredentialStore
</h1>
<p align="center">
🔐 A simple cross-platform credential manager for PSCredential objects.
</p>
<p align="center">
<a href="https://drone.ocram85.com/OCram85/PSCredentialStore">
<img
src="https://drone.ocram85.com/api/badges/OCram85/PSCredentialStore/status.svg"
alt="Master Branch Build Status"
>
</a>
<!-- CodeCove disabled for self hosting git
<a href="https://codecov.io/gh/OCram85/PSCredentialStore">
<img src="https://codecov.io/gh/OCram85/PSCredentialStore/branch/master/graph/badge.svg" alt="CodeCov">
</a>
-->
<a href="https://www.powershellgallery.com/packages/PSCredentialStore">
<img
src="https://img.shields.io/powershellgallery/v/PSCredentialStore.svg?style=plastic"
alt="PowershellGallery Published Version"
>
</a>
<a href="https://www.powershellgallery.com/packages/PSCredentialStore">
<img
src="https://img.shields.io/powershellgallery/vpre/PSCredentialStore.svg?label=latest%20preview&style=plastic"
>
</a>
<a href="https://www.powershellgallery.com/packages/PSCredentialStore">
<img
src="https://img.shields.io/powershellgallery/dt/PSCredentialStore.svg?style=plastic"
>
</a>
</p>
## :key: General
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 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.
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.
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 Gitea or via CLI with
`Get-Help about_PSCredentialStore`.
You can find the full [reference](docs/Readme.md) in the */docs/* path as well.
## :vulcan_salute: Requirements
- PowerShell >= `5.1`
- .NET Framework >= `4.6` or .NET Core >= `1.0`
## :bomb: About Security
> This section explains some security topics and 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 a brief hierarchy description for the certificate lookup order: *(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 5.1 or higher with `$PSVersionTable`.
* Use the builtin PackageManagement + PowerShellGet module and install PSCredentialStore 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`
### :building_construction: Manual Way
* Take a look at the [Latest Release](https://gitea.ocram85.com/OCram85/PSCredentialStore/releases/latest) page.
* Download the `PSCredentialStore.zip`.
* Unpack the zip file and put it in your Powershell module path.
* Don't forget to change the NTFS permission flag in the context menu.
* Start with `Import-Module PSCredentialStore`
### :sparkles: Quick Start
**1.** First we need a blank credential store. You can decide between a *private* or *shared* one.
> :bulb: Note: The private 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
# Private credential store
New-CredentialStore
# Private credential store with certificate store usage
New-CredentialStore -UseCertStore
# Shared credential store
New-CredentialStore -Shared
# Shared credential store in custom location
New-CredentialStore -Shared -Path 'C:\CredentialStore.json'
```
**2.** Now you can manage your credential store items:
```powershell
# This will prompt for credentials and stores it in a private store
New-CredentialStoreItem -RemoteHost 'dc01.myside.local' -Identifier 'AD'
# You can now use it in other scripts like this:
$DCCreds = Get-CredentialStoreItem -RemoteHost 'dc01.myside.local' -Identifier 'AD'
Invoke-Command -ComputerName 'dc01.myside.local' -Credential $DCCreds -ScripBlock {Get-Process}
```
The credential store contains also a simple function to establish a connection with several systems or protocols.
If you have already installed the underlying framework / modules, you can connect to these endpoint types:
* **CiscoUcs** - Establish a connection to a Cisco UCS fabric interconnect.
* Required Modules: [`Cisco.UCS.Core`, `Cisco.UCSManager`](https://software.cisco.com/download/release.html?i=!y&mdfid=286305108&softwareid=284574017&release=2.1.1)
* **FTP** - Establish a connection to a FTP host.
* Required Modules: [`WinSCP`](https://www.powershellgallery.com/packages/WinSCP)
* **NetAppFAS** - Establish a connection to a NetApp Clustered ONTAP filer.
* Required Modules: [`DataONTAP`](http://mysupport.netapp.com/tools/info/ECMLP2310788I.html?productID=61926)
* **VMware** - Establish a connection to a VMware vCenter or ESXi host.
* Required Modules: [`VMware.VimAutomation.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI)
* **CisServer** - Establish a connection to the CisServer Service on vCenter Host.
* 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:
```powershell
Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs
Connect-To -RemoteHost "ftp.myside.local" -Type FTP
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
Connect-To -RemoteHost "esx01.myside.local" -Type VMware
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)!

View File

@ -1,56 +0,0 @@
version: 0.1.{build}
branches:
only:
- master
- dev
- debug
skip_tags: true
#image: WMF 5
# Test ne build image:
image: Visual Studio 2017
# Install pester module and init the Appveyor support.
install:
- ps: Install-PackageProvider -Name NuGet -MinimumVersion '2.8.5.201' -Force -Verbose
- ps: Import-PackageProvider NuGet -MinimumVersion '2.8.5.201' -Force
- ps: Install-Module -Name 'Pester' -Scope CurrentUser -Force -SkipPublisherCheck -AllowClobber
- ps: Update-Module 'Pester'
- ps: Install-Module -Name 'posh-git' -Scope CurrentUser -Force -SkipPublisherCheck -AllowClobber
- ps: Update-Module 'posh-git'
- ps: Install-Module -Name 'PSCoverage' -Scope CurrentUser -Force -SkipPublisherCheck -AllowClobber
- ps: Import-Module 'PSCoverage'
- ps: Import-Module .\tools\AppVeyor.psm1
environment:
NuGetToken:
secure: 835qfZIkC9mE7QhkYfOZVAdR8rZhPvxG8BO4CbeaelRQOhlqmaSr8G1DWRJzZ/bS
CoverallsToken:
secure: eTjWqHL48MBr8wp1rSgLrXHdtpfDV/uClacP3svlWJfCvn/zVokpuaMnWM5RoyIY
build: false
before_build:
- ps: Invoke-AppVeyorBumpVersion
build_script:
- ps: Invoke-AppVeyorBuild
test_script:
- ps: Invoke-AppVeyorTests
- ps: Invoke-CoverageReport
deploy:
- provider: GitHub
auth_token:
secure: M+bBX5/nKdJB0eViP7xtrLVTwf3vGDUA9N2MMprZp2i+9ZR3CBVcJnSzJWUmalhB
artifact: PSCredentialStore.zip # upload all NuGet packages to release assets
draft: false
prerelease: true
on:
branch: master # release from master branch only
after_deploy:
- ps: Invoke-AppVeyorPSGallery

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

0
build/.gitkeep Normal file
View File

1
docs/.gitkeep Normal file
View File

@ -0,0 +1 @@
This is a placeholder file.

209
docs/Connect-To.md Normal file
View File

@ -0,0 +1,209 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Connect-To
## SYNOPSIS
Connects to the given host using the stored CredentialStoreItem.
## SYNTAX
### Private (Default)
```
Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] [-PassThru]
[<CommonParameters>]
```
### Shared
```
Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] [-Shared]
[-Path <String>] [-PassThru] [<CommonParameters>]
```
## DESCRIPTION
Establish a connection to the selected host using a stored CredentialStoreItem.
## EXAMPLES
### EXAMPLE 1
```
Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs
```
### EXAMPLE 2
```
Connect-To -RemoteHost "ucscentral.myside.local" -Type 'CiscoUcsCentral'
```
### EXAMPLE 3
```
Connect-To -RemoteHost "ftp.myside.local" -Type FTP
```
### EXAMPLE 4
```
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
```
### EXAMPLE 5
```
Connect-To -RemoteHost "esx01.myside.local" -Type VMware
```
### EXAMPLE 6
```
Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer
```
### EXAMPLE 7
```
Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
```
### EXAMPLE 8
```
Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
```
## PARAMETERS
### -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
Position: Named
Default value: None
Accept pipeline input: 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
```
### -PassThru
Returns the value from the underlying connection type function.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: 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
Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Type
Specify the host type of the target.
Currently implemented targets are: Possible connection values are:
- CiscoUcs
- CiscoUcsCentral
- CisServer
- ExchangeHTTP
- ExchangeHTTPS
- FTP
- NetAppFAS
- SCP
- VMware
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
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
### [None]
## OUTPUTS
### [None]
## NOTES
## RELATED LINKS

133
docs/Disconnect-From.md Normal file
View File

@ -0,0 +1,133 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Disconnect-From
## SYNOPSIS
Terminates a session established with Connect-To using a CredentialStoreItem.
## SYNTAX
```
Disconnect-From [-RemoteHost] <String> [-Type] <String> [-Force] [<CommonParameters>]
```
## DESCRIPTION
Terminates a session established with Connect-To using a CredentialStoreItem.
## EXAMPLES
### EXAMPLE 1
```
Disconnect-From -RemoteHost "ucs.myside.local" -Type CiscoUcs
```
### EXAMPLE 2
```
Disconnect-From -RemoteHost "ftp.myside.local" -Type FTP
```
### EXAMPLE 3
```
Disconnect-From -RemoteHost "fas.myside.local" -Type NetAppFAS
```
### EXAMPLE 4
```
Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware
```
### EXAMPLE 5
```
Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware -Force:$True
```
### EXAMPLE 6
```
Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer
```
### EXAMPLE 7
```
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
```
### EXAMPLE 8
```
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
```
## 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
Specify the remote endpoint, whose session you would like to terminate.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Type
Specify the host type of the target.
Currently implemented targets are:
- CiscoUcs
- CiscoUcsCentral
- FTP
- NetAppFAS
- VMware
- CisServer
- ExchangeHTTP
- ExchangeHTTPS
- SCP
```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
### [None]
## NOTES
## RELATED LINKS

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

@ -0,0 +1,72 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# 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
### EXAMPLE 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
## RELATED LINKS

View File

@ -0,0 +1,84 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Get-CredentialStore
## SYNOPSIS
Reads the complete content of the credential store and returns it as a new object.
## SYNTAX
### Private (Default)
```
Get-CredentialStore [<CommonParameters>]
```
### Shared
```
Get-CredentialStore [-Path <String>] [-Shared] [<CommonParameters>]
```
## DESCRIPTION
The content is in a raw format.
It means there is no transformation to the different credential types.
You can not use the object properties to connect with remote host.
Therefore please use
Get-CredentialStoreItem.
## EXAMPLES
### EXAMPLE 1
```
$CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json"
```
## PARAMETERS
### -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
```
### -Shared
Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
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
### [PSObject] Returns the credential store content as PSObject.
## NOTES
## RELATED LINKS

View File

@ -0,0 +1,114 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Get-CredentialStoreItem
## SYNOPSIS
Returns the Credential from a given remote host item.
## SYNTAX
### Private (Default)
```
Get-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonParameters>]
```
### Shared
```
Get-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Shared] [-Path <String>]
[<CommonParameters>]
```
## DESCRIPTION
Return the credential as PSCredential object.
## EXAMPLES
### EXAMPLE 1
```
$myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
```
## PARAMETERS
### -Identifier
Provide a custom identifier to the given remote host key.
This enables you to store multiple credentials
for a single remote host entry.
For example ad/sys1, ftp/sys1, mssql/sys1
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: 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
Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
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
### [System.Management.Automation.PSCredential]
## NOTES
## RELATED LINKS

View File

@ -0,0 +1,73 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# 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
### EXAMPLE 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
## RELATED LINKS

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

@ -0,0 +1,156 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# 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
### EXAMPLE 1
```
$AttribParams = @{
Country = 'DE'
State = 'BW'
City = 'Karlsruhe'
Organization ='AwesomeIT'
OrganizationalUnitName ='PSCredentialStore'
CommonName ='MyPrivateCert'
}
New-CSCertAttribute @AttribParams
```
## 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
## RELATED LINKS

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

@ -0,0 +1,121 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# 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
### EXAMPLE 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
## RELATED LINKS

203
docs/New-CredentialStore.md Normal file
View File

@ -0,0 +1,203 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# New-CredentialStore
## SYNOPSIS
Creates a new credential store File
## SYNTAX
### Private (Default)
```
New-CredentialStore [-Force] [-PassThru] [-SkipPFXCertCreation] [-UseCertStore] [-WhatIf] [-Confirm]
[<CommonParameters>]
```
### Shared
```
New-CredentialStore [-Shared] [-Path <FileInfo>] [-Force] [-PassThru] [-SkipPFXCertCreation] [-UseCertStore]
[-WhatIf] [-Confirm] [<CommonParameters>]
```
## DESCRIPTION
You need to run this script first to create a new credential store before you try to
save new credentials with New-CredentialStoreItem.
## EXAMPLES
### EXAMPLE 1
```
New-CredentialStore
# Creates a new private CredentialStore
```
### EXAMPLE 2
```
New-CredentialStore -Force
# Resets an existing private CredentialStore
```
### EXAMPLE 3
```
New-CredentialStore -Shared
# Creates a new shared CredentialStore
```
### EXAMPLE 4
```
New-CredentialStore -Shared -Path "C:\TMP\CredentialStore.json"
# Creates a new shared CredentialStore in the given location.
```
## PARAMETERS
### -Force
Use this switch to reset an existing store.
The complete content will be wiped.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -PassThru
{{ Fill PassThru Description }}
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path
Define a location for the new shared CredentialStore.
The default store will be created in
$Env:ProgramData\PSCredentialStore dir.
```yaml
Type: FileInfo
Parameter Sets: Shared
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared
Creates a CredentialStore in the Shared mode.
This enables you to read the CredentialStore Items on
different systems or profiles.
In addition you can optionally provide a custom path wit the -Path parameter.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
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
Position: Named
Default value: False
Accept pipeline input: 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
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.Store'] Returns the recently created CredentialStore object if the -PassThru parameter
### was given.
## NOTES
## RELATED LINKS

View File

@ -0,0 +1,134 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# New-CredentialStoreItem
## SYNOPSIS
Adds a credential store item containing host, user and password to the given store.
## SYNTAX
### Private (Default)
```
New-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>]
[<CommonParameters>]
```
### Shared
```
New-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>] [-Shared]
[-Path <String>] [<CommonParameters>]
```
## DESCRIPTION
The credentials are stored without any relations to it's further use.
If you need to change an existing
item please use Set-CredentialStoreItem.
You need to decide afterwards, whether to use the credential for
a VIConnection, NetApp FAS or UCS Fabric Interconnect.
## EXAMPLES
### EXAMPLE 1
```
New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
```
## PARAMETERS
### -Credential
You can provide credentials optionally as pre existing pscredential object.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -Identifier
Provide a custom identifier to the given remote host key.
This enables you to store multiple credentials
for a single remote host entry.
For example ad/sys1, ftp/sys1, mssql/sys1
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path
Define the store in which you would like to add a new item.
```yaml
Type: String
Parameter Sets: Shared
Aliases:
Required: False
Position: Named
Default value: None
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
Accept pipeline input: False
Accept wildcard characters: False
```
### -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.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
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
## RELATED LINKS

64
docs/Readme.md Normal file
View File

@ -0,0 +1,64 @@
---
Module Name: PSCredentialStore
Module Guid: 6800e192-9df8-4e30-b253-eb2c799bbe84
Download Help Link: {{ Update Download Link }}
Help Version: {{ Please enter version of help manually (X.X.X.X) format }}
Locale: en-US
---
# PSCredentialStore Module
## Description
See global Readme file for usage instructions.
## PSCredentialStore Cmdlets
### [Connect-To](Connect-To.md)
Connects to the given host using the stored CredentialStoreItem.
### [Disconnect-From](Disconnect-From.md)
Terminates a session established with Connect-To using a CredentialStoreItem.
### [Get-CredentialStore](Get-CredentialStore.md)
Reads the complete content of the credential store and returns it as a new object.
### [Get-CredentialStoreItem](Get-CredentialStoreItem.md)
Returns the Credential from a given remote host item.
### [Get-CSCertificate](Get-CSCertificate.md)
Returns the current used valid PfX certificate.
### [Import-CSCertificate](Import-CSCertificate.md)
Imports a linked certificate to the valid store location.
### [New-CredentialStore](New-CredentialStore.md)
Creates a new credential store File
### [New-CredentialStoreItem](New-CredentialStoreItem.md)
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 the given credentials from the credential store.
### [Set-CredentialStoreItem](Set-CredentialStoreItem.md)
Changes the credentials for the given remote host in the store.
### [Test-CredentialStore](Test-CredentialStore.md)
Returns the credential store state.
### [Test-CredentialStoreItem](Test-CredentialStoreItem.md)
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

@ -0,0 +1,128 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Remove-CredentialStoreItem
## SYNOPSIS
Remove the given credentials from the credential store.
## SYNTAX
### Private (Default)
```
Remove-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonParameters>]
```
### Shared
```
Remove-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Shared] [-Path <String>]
[<CommonParameters>]
```
## DESCRIPTION
Use this CMDLet to completely remove an credential store item.
## EXAMPLES
### EXAMPLE 1
```
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local"
```
### EXAMPLE 2
```
Remove-CredentialStoreItem -Shared -RemoteHost "esx01.myside.local"
```
### EXAMPLE 3
```
Remove-CredentialStoreItem -Shared -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
```
### EXAMPLE 4
```
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local" -Identifier svc
```
## 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
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
Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
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
## RELATED LINKS

View File

@ -0,0 +1,134 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Set-CredentialStoreItem
## SYNOPSIS
Changes the credentials for the given remote host in the store.
## SYNTAX
### Private (Default)
```
Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>]
[<CommonParameters>]
```
### Shared
```
Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>] [-Shared]
[-Path <String>] [<CommonParameters>]
```
## DESCRIPTION
Use this function to update your already stored RemoteHost items.
## EXAMPLES
### EXAMPLE 1
```
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
```
### EXAMPLE 2
```
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
```
## PARAMETERS
### -Credential
Provided the new credentials you want to update inside the RemoteHost item.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
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
```
### -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
Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
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
## RELATED LINKS

View File

@ -0,0 +1,57 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# 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
### EXAMPLE 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
## RELATED LINKS

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

@ -0,0 +1,74 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# 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
### EXAMPLE 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
## RELATED LINKS

View File

@ -0,0 +1,81 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Test-CredentialStore
## SYNOPSIS
Returns the credential store state.
## SYNTAX
### Private (Default)
```
Test-CredentialStore [<CommonParameters>]
```
### Shared
```
Test-CredentialStore [-Path <String>] [-Shared] [<CommonParameters>]
```
## DESCRIPTION
Use this script to test your credential store.
For now it only checks if
the file exists.
## EXAMPLES
### EXAMPLE 1
```
Test-CredentialStore -eq $true
```
## PARAMETERS
### -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
```
### -Shared
Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
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
## OUTPUTS
### System.Boolean
## NOTES
## RELATED LINKS

View File

@ -0,0 +1,127 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# Test-CredentialStoreItem
## SYNOPSIS
Checks if the given RemoteHost identifier combination exists in the credential store.
## SYNTAX
### Private (Default)
```
Test-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonParameters>]
```
### Shared
```
Test-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared]
[<CommonParameters>]
```
## DESCRIPTION
Use this cmdlet for basic checks with a single item.
Check the item first with this function before
you try to interact with it.
Breaking Change for \`v1.1.0+\`:
Test-CredentialStoreItem will return \`$false\` even if the store doesn't exist.
We removed the terminating
error and replaced it with a warning message.
## EXAMPLES
### EXAMPLE 1
```
if (Test-CredentialStoreItem -RemoteHost "Default") {
Get-CredentialStoreItem -RemoteHost "Default"
}
else {
Write-Warning ("The given Remote Host {0} does not exist in the credential Store!" -f $RemoteHost)
}
```
## 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
Define a custom credential store you try to read from.
Without the \`-Path\` parameter
\`Test-CredentialStoreItem\` tries to read from the default private store.
```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
```
### -Shared
Switch to shared mode with this param.
This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
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
## RELATED LINKS

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

@ -0,0 +1,108 @@
---
external help file: ModuleRoot-help.xml
Module Name: PSCredentialStore
online version:
schema: 2.0.0
---
# 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
### EXAMPLE 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
## RELATED LINKS

View File

@ -0,0 +1,147 @@
# PSCredentialStore
## about_PSCredentialStore
# SHORT DESCRIPTION
PSCredentialStore enables managing multiple PSCredential objects.
# LONG DESCRIPTION
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
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.
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.
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 gitea 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
## PowerShellGallery.com (Recommended Way)
* Make sure you use PowerShell 5.1 or higher with `$PSVersionTable`.
* Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore`
* Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore`
## Manual Way
* Take a look at the [Latest Release](https://github.com/OCram85/PSCredentialStore/releases/latest) page.
* Download the `PSCredentialStore.zip`.
* Unpack the Zip and put it in your Powershell Module path.
* Don't forget to change the NTFS permission flag in the context menu.
* Start with `Import-Module PSCredentialStore`
**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.
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
# Private credential store
New-CredentialStore
# Private credential store with certificate store usage
New-CredentialStore -UseCertStore
# Shared credential store
New-CredentialStore -Shared
#Shared credential store in custom Location
New-CredentialStore -Shared -Path 'C:\CredentialStore.json'
```
**2.** Now you can manage your CredentialStoreItems:
```powershell
# This will prompt for credentials and stores it in a private store
New-CredentialStoreItem -RemoteHost 'dc01.myside.local' -Identifier 'AD'
# You can now use it in other scripts like this:
$DCCreds = Get-CredentialStoreItem -RemoteHost 'dc01.myside.local' -Identifier 'AD'
Invoke-Command -ComputerName 'dc01.myside.local' -Credential $DCCreds -ScripBlock {Get-Process}
```
The CredentialStore contains also a simple function to establish a connection with several systems or protocols.
If you have already installed the underlying framework your can connect to:
* **CiscoUcs** - Establish a connection to a Cisco UCS fabric interconnect.
* Required Modules: [`Cisco.UCS.Core`, `Cisco.UCSManager`](https://software.cisco.com/download/release.html?i=!y&mdfid=286305108&softwareid=284574017&release=2.1.1)
* **FTP** - Establish a connection to a FTP host.
* Required Modules: [`WinSCP`](https://www.powershellgallery.com/packages/WinSCP)
* **NetAppFAS** - Establish a connection to a NetApp Clustered ONTAP filer.
* Required Modules: [`DataONTAP`](http://mysupport.netapp.com/tools/info/ECMLP2310788I.html?productID=61926)
* **VMware** - Establish a connection to a VMware vCenter or ESXi host.
* Required Modules: [`VMware.VimAutomation.Core`](https://www.powershellgallery.com/packages/VMware.PowerCLI)
* **CisServer** - Establish a connection to the CisServer Service on vCenter Host.
* 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
```powershell
Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs
Connect-To -RemoteHost "ftp.myside.local" -Type FTP
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
Connect-To -RemoteHost "esx01.myside.local" -Type VMware
Connect-To -RemoteHost "vcr.myside.local" -Type CisServer
```
# NOTE
# TROUBLESHOOTING NOTE
# SEE ALSO
# KEYWORDS
- Credential
- Store

View File

@ -0,0 +1,139 @@
@{
Severity = 'Error', 'Warning', 'Information'
IncludeRules = @(
'PSAlignAssignmentStatement',
'PSAvoidAssignmentToAutomaticVariable',
'AvoidDefaultValueForMandatoryParameter',
'PSAvoidDefaultValueSwitchParameter',
'PSAvoidGlobalAliases',
'ÜSAvoidGlobalFunctions',
'PSAvoidGlobalVars',
'PSAvoidInvokingEmptyMembers',
'PSAvoidLongLines',
'PSAvoidNullOrEmptyHelpMessageAttribute',
'PSAvoidOverwritingBuiltInCmdlets',
'PSAvoidShouldContinueWithoutForce',
'PSAvoidTrailingWhitespace',
'PSAvoidUsingCmdletAliases',
'PSAvoidUsingComputerNameHardcoded',
'PSAvoidUsingConvertToSecureStringWithPlainText',
'PSAvoidUsingDeprecatedManifestFields',
'PSAvoidUsingDoubleQuotesForConstantString',
'PSAvoidUsingEmptyCatchBlock',
'PSAvoidUsingInvokeExpression',
'PSAvoidUsingPlainTextForPassword',
'PSAvoidUsingPositionalParameters',
'PSAvoidUsingUsernameAndPasswordParams',
'PSAvoidUsingWMICmdlet',
'PSAvoidUsingWriteHost',
'PSMisleadingBacktick',
'PSMissingModuleManifestField',
'PSPlaceCloseBrace',
'PSPlaceOpenBrace',
'PSPossibleIncorrectComparisonWithNull',
'PSPossibleIncorrectUsageOfAssignmentOperator',
'PSPossibleIncorrectUsageOfRedirectionOperator',
'PSProvideCommentHelp',
'PSReservedCmdletChar',
'PSReservedParams',
'PSReviewUnusedParameter',
'PSShouldProcess',
'PSUseApprovedVerbs',
'PSUseBOMForUnicodeEncodedFile',
'PSUseCmdletCorrectly',
'PSUseCompatibleCmdlets',
#'PSUseCompatibleCommands',
'PSUseCompatibleSyntax',
#'PSUseCompatibleTypes',
'PSUseConsistentIndentation',
'PSUseConsistentWhitespace',
'PSUseCorrectCasing',
'PSUseDeclaredVarsMoreThanAssignments',
'PSUseLiteralInitializerForHashtable',
'PSUseOutputTypeCorrectly',
'PSUsePSCredentialType',
'PSUseProcessBlockForPipelineCommand',
'PSUseShouldProcessForStateChangingFunctions',
'PSUseSingularNouns',
'PSUseSupportsShouldProcess',
'PSUseToExportFieldsInManifest',
'PSUseUTF8EncodingForHelpFile',
'PSUseUsingScopeModifierInNewRunspaces'
)
Rules = @{
PSAvoidLongLines = @{
Enable = $true
MaximumLineLength = 116
}
PSPlaceOpenBrace = @{
Enable = $true
OnSameLine = $true
NewLineAfter = $true
IgnoreOneLineBlock = $true
}
PSPlaceCloseBrace = @{
Enable = $true
NewLineAfter = $true
IgnoreOneLineBlock = $true
NoEmptyLineBefore = $false
}
PSProvideCommentHelp = @{
Enable = $true
ExportedOnly = $false
BlockComment = $true
VSCodeSnippetCorrection = $false
Placement = "begin"
}
PSUseCompatibleCmdlets = @{
compatibility = @(
"desktop-5.1.14393.206-windows",
"core-6.1.0-windows"
)
}
PSUseCompatibleSyntax = @{
Enable = $true
TargetVersions = @(
"7.0",
"5.1"
)
}
PSUseConsistentIndentation = @{
Enable = $true
Kind = 'space'
PipelineIndentation = 'IncreaseIndentationForFirstPipeline'
IndentationSize = 4
}
PSUseConsistentWhitespace = @{
Enable = $true
CheckInnerBrace = $true
CheckOpenBrace = $true
CheckOpenParen = $true
CheckOperator = $true
CheckPipe = $true
CheckPipeForRedundantWhitespace = $false
CheckSeparator = $true
CheckParameter = $false
IgnoreAssignmentOperatorInsideHashTable = $true
}
PSAlignAssignmentStatement = @{
Enable = $true
CheckHashtable = $false
}
PSUseCorrectCasing = @{
Enable = $true
}
}
}

View File

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

View File

@ -1 +0,0 @@
!マ<><EFBE8F>H4サ<34><EFBDBB>"=w肛Sヨ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,66 @@
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'
#>
[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,64 @@
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')
#>
[CmdletBinding()]
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,20 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
}
Describe "New-CSCertAttribute" {
Context "Basis Tests" -Tag 'Unit' {
It "Should not throw" {
$AttribParams = @{
Country = 'DE'
State = 'BW'
City = 'KA'
Organization = 'IT'
OrganizationalUnitName = 'foo'
CommonName = 'MyCert'
}
{ New-CSCertAttribute @AttribParams } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,103 @@
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
$AttribParams = @{
Country = 'DE'
State = 'BW'
City = 'Karlsruhe'
Organization ='AwesomeIT'
OrganizationalUnitName ='PSCredentialStore'
CommonName ='MyPrivateCert'
}
New-CSCertAttribute @AttribParams
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions',
'',
Justification = 'Returns a new object and does not change data'
)]
[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,33 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
Describe "New-CSCertificate" {
Context "Basic Tests" -Tag 'Unit' {
It "Should not throw" {
$attribs = @{
Country = 'DE'
State = 'BW'
City = 'KA'
Organization = 'IT'
OrganizationalUnitName = 'foo'
CommonName = 'MyCert'
}
$CertAttribs = @{
CRTAttribute = New-CSCertAttribute @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

@ -0,0 +1,146 @@
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'
#>
[CmdletBinding(SupportsShouldProcess = $true)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingInvokeExpression',
'',
Justification = 'needed for openssl wrapping'
)]
[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/libressl/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,87 @@
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'
#>
[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 -Message (
'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) {
$PFXParams = @{
Thumbprint = $CS.Thumbprint
StoreName = 'Root'
StoreLocation = 'LocalMachine'
}
$cert = Get-CSPfxCertificate @PFXParams
}
}
elseif ( (! $isLinux) -or ($isWindows) ) {
$PFXParams = @{
Thumbprint = $CS.Thumbprint
StoreName = 'My'
StoreLocation = 'LocalMachine'
}
$cert = Get-CSPfxCertificate @PFXParams
if ($null -eq $cert) {
$PFXParams = @{
Thumbprint = $CS.Thumbprint
StoreName = 'Root'
StoreLocation = 'LocalMachine'
}
$cert = Get-CSPfxCertificate @PFXParams
}
}
}
if ($null -eq $cert) {
return $false
}
else {
return $true
}
}
end {
}
}

View File

@ -0,0 +1,113 @@
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'
#>
[CmdletBinding(DefaultParameterSetName = 'Private')]
[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,44 +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,11 +14,17 @@ function Connect-To {
same hostname.
.PARAMETER Type
Specify the host type of the target. 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.
Specify the host type of the target. Currently implemented targets are: Possible connection values are:
- CiscoUcs
- CiscoUcsCentral
- CisServer
- ExchangeHTTP
- ExchangeHTTPS
- FTP
- NetAppFAS
- SCP
- VMware
.PARAMETER Credentials
Use this parameter to bypass the stored credentials. Without this parameter Connect-To tries to read the
@ -32,6 +38,9 @@ function Connect-To {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
.PARAMETER PassThru
Returns the value from the underlying connection type function.
.INPUTS
[None]
@ -40,56 +49,87 @@ function Connect-To {
.EXAMPLE
Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs
.EXAMPLE
Connect-To -RemoteHost "ucscentral.myside.local" -Type 'CiscoUcsCentral'
.EXAMPLE
Connect-To -RemoteHost "ftp.myside.local" -Type FTP
.EXAMPLE
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
.EXAMPLE
Connect-To -RemoteHost "esx01.myside.local" -Type VMware
.EXAMPLE
$MyCreds = Get-Credential
Connect-To -RemoteHost "vcr01.myside.local" -Type VMware -Credentials $MyCreds
Get-VM -Name "*vlm*" | Select-Object -Property Name
Disconnect-From -RemoteHost "vcr01.myside.local" -Type VMware
Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer
.NOTES
File Name : Connect-To.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires : PSFTP, PowerCLI
.EXAMPLE
Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
.LINK
https://github.com/OCram85/PSCredentialStore
.EXAMPLE
Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
param(
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[String]$RemoteHost,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[String]$Identifier,
[CmdletBinding(DefaultParameterSetName = 'Private')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidGlobalVars',
'',
Justification = 'Wrapping existing var from WinSCP module.'
)]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $true, ParameterSetName = 'Private')]
[string]$RemoteHost,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[ValidateSet("CiscoUcs", "FTP", "NetAppFAS", "VMware")]
[String]$Type,
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $false, ParameterSetName = 'Private')]
[string]$Identifier,
[Parameter(Mandatory = $False, ParameterSetName = "Shared")]
[Parameter(Mandatory = $False, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $true, ParameterSetName = 'Private')]
[ValidateSet(
'CiscoUcs',
'CiscoUcsCentral',
'FTP',
'NetAppFAS',
'VMware',
'CisServer',
'ExchangeHTTP',
'ExchangeHTTPS',
'SCP'
)]
[string]$Type,
[Parameter(Mandatory = $False, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $False, ParameterSetName = 'Private')]
[PSCredential]$Credentials,
[Parameter(Mandatory = $False, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()]
[String]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetNAme = 'Shared')]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetNAme = "Shared")]
[Switch]$Shared
[Parameter(Mandatory = $False, ParameterSetName = 'Shared')]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory = $False, ParameterSetName = 'Private')]
[Parameter(Mandatory = $False, ParameterSetName = 'Shared')]
[switch]$PassThru
)
begin {
# First check the optional modules
if (-not (Resolve-Dependency -Name $Type)) {
Write-Error -Message ("Could not resolve the optional dependencies defined for {0}" -f $Type) -ErrorAction 'Stop'
# 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
}
}
switch ($Type) {
"VMware" {
# Disable the yellow certificate warning, since we haven't replaced the SSL certs for vCenter/ESXi
@ -102,10 +142,6 @@ function Connect-To {
}
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)) {
# 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.
@ -115,48 +151,76 @@ function Connect-To {
try {
if ($Identifier -ne "") {
$RemoteHostIdentifier = "{0}/{1}" -f $Identifier, $RemoteHost
$creds = Get-CredentialStoreItem -RemoteHost $RemoteHostIdentifier -Path $Path
$creds = Get-CredentialStoreItem -Shared -RemoteHost $RemoteHostIdentifier -Path $Path
}
else {
$creds = Get-CredentialStoreItem -RemoteHost $RemoteHost -Path $Path
$creds = Get-CredentialStoreItem -Shared -RemoteHost $RemoteHost -Path $Path
}
}
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 {
$creds = $Credentials
}
if ($creds.UserName -eq "" -or $creds.Password.GetType().Name -ne "SecureString") {
# Write a error message to the log.
Write-Message2 ("Please provide valid credentials for RemoteHost {0}!" -f $RemoteHost) -ErrorAction Stop
if ($creds.UserName -eq "" -or $creds.Password.GetType().Name -ne 'SecureString') {
$MessageParams = @{
Message = "Please provide valid credentials for RemoteHost {0}!" -f $RemoteHost
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
else {
switch ($Type) {
"CiscoUcs" {
try {
$handle = Connect-Ucs -Name $RemoteHost -Credential $creds -ErrorAction Stop
$ExecutionContext.SessionState.PSVariable.Set("DefaultUcs", $handle)
$handle = Connect-Ucs -Name $RemoteHost -Credential $creds -ErrorAction 'Stop' -NotDefault
$ExecutionContext.SessionState.PSVariable.Set('DefaultUcs', $handle)
}
catch {
# Write a error message to the log.
Write-Message2 ("Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type) -ErrorAction Stop
$MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
"CiscoUcsCentral" {
try {
$handle = Connect-UcsCentral -Name $RemoteHost -Credential $creds -NotDefault
$ExecutionContext.SessionState.PSVariable.Set('DefaultUcsCentral', $handle)
}
catch {
$MessageParams = @{
Message = ('Unable to connect to {0} using {1}' -f $RemoteHost, $Type)
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
"FTP" {
# First establish the FTP session
$WinSCPConParams = @{
Credential = $creds
Hostname = $RemoteHost
Protocol = 'Ftp'
FtpMode = 'Passive'
Hostname = $RemoteHost
Protocol = 'Ftp'
FtpMode = 'Passive'
}
try {
$Global:WinSCPSession = New-WinSCPSession @WinSCPConParams
$FTPSessionOption = New-WinSCPSessionOption @WinSCPConParams
$Global:WinSCPSession = New-WinSCPSession -SessionOption $FTPSessionOption
}
catch {
throw "Could not connect to {0} using {1} protocol!" -f $RemoteHost, $Type
@ -165,8 +229,11 @@ function Connect-To {
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"
Message = (
("Connection to {0} using Type {1} " -f $RemoteHost, $Type) +
"was established. But now it seems to be lost!"
)
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
@ -179,8 +246,8 @@ function Connect-To {
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "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
}
@ -193,8 +260,103 @@ function Connect-To {
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "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
}
}
"CisServer" {
try {
if ($PassThru.IsPresent) {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop
}
else {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop | Out-Null
}
}
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
}
}
"ExchangeHTTP" {
try {
$ConnectionParams = @{
ConnectionURI = "http://{0}/powershell" -f $RemoteHost
ConfigurationName = 'Microsoft.Exchange'
Credential = $creds
ErrorAction = 'Stop'
}
$Global:PSExchangeRemote = New-PSSession @ConnectionParams
# ScriptAnalyzer issue (unused var) workaround.
$null = $Global:PSExchangeRemote
}
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. " -f $RemoteHost, $Type) +
"But now it seems to be lost!"
)
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
@ -202,8 +364,8 @@ function Connect-To {
default {
# Write a error message to the log.
$MessageParams = @{
Message = "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
}

View File

@ -15,10 +15,16 @@ function Disconnect-From {
.PARAMETER Type
Specify the host type of the target. 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.
- CiscoUcs
- CiscoUcsCentral
- FTP
- NetAppFAS
- VMware
- CisServer
- ExchangeHTTP
- ExchangeHTTPS
- SCP
.PARAMETER Force
Force the disconnect, even if the disconnect would fail.
@ -44,104 +50,184 @@ function Disconnect-From {
.EXAMPLE
Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware -Force:$True
.NOTES
File Name : Disconnect-To.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.EXAMPLE
Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer
.LINK
https://github.com/OCram85/PSCredentialStore
.EXAMPLE
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
.EXAMPLE
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
#>
[CmdletBinding()]
param(
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidGlobalVars',
'',
Justification = 'Wrapping existing global vars from external modules'
)]
param (
[Parameter(Mandatory = $true)]
[string]$RemoteHost,
[Parameter(Mandatory = $true)]
[ValidateSet("CiscoUcs", "FTP", "NetAppFAS", "VMware")]
[ValidateSet(
'CiscoUcs',
'CiscoUcsCentral',
'FTP',
'NetAppFAS',
'VMware',
'CisServer',
'ExchangeHTTP',
'ExchangeHTTPS',
'SCP'
)]
[string]$Type,
[Parameter(Mandatory = $false)]
[switch]$Force
)
switch ($Type) {
"VMware" {
try {
if ($Force) {
Disconnect-VIServer -Server $RemoteHost -Confirm:$false -ErrorAction Stop -Force:$true
begin {}
process {
switch -Regex ($Type) {
"VMware" {
try {
if ($Force) {
Disconnect-VIServer -Server $RemoteHost -Confirm:$false -ErrorAction 'Stop' -Force:$true
}
else {
Disconnect-VIServer -Server $RemoteHost -Confirm:$false -ErrorAction 'Stop'
}
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
"CisServer" {
try {
if ($Force) {
Disconnect-CisServer -Server $RemoteHost -Confirm:$false -ErrorAction 'Stop' -Force:$true
}
else {
Disconnect-CisServer -Server $RemoteHost -Confirm:$false -ErrorAction 'Stop'
}
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
# Check for an existing WinSCP Session var
"FTP" {
if ($Global:WinSCPSession.Opened) {
Remove-WinSCPSession -WinSCPSession $Global:WinSCPSession
}
else {
Disconnect-VIServer -Server $RemoteHost -Confirm:$false -ErrorAction Stop
$MessageParams = @{
Message = 'There is no open WinSCP Session'
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
# DataONTAP doesn't have a CmdLet `Disconnect-NcController`.
# So we go ahead and clear the CurrentNcController variable.
"NetAppFAS" {
try {
$MessageParams = @{
Message = (
"Setting {0} to `$null, which will disconnect NetAppFAS" -f $Global:CurrentNcController
)
ErrorAction = 'Continue'
}
Write-Verbose @MessageParams
$Global:CurrentNcController = $null
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
"CiscoUcs" {
try {
Disconnect-Ucs -Ucs $RemoteHost
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
"CiscoUCSCentral" {
try {
$handle = Connect-UcsCentral -Name $RemoteHost -Credential $creds -NotDefault
$ExecutionContext.SessionState.PSVariable.Set('DefaultUcsCentral', $handle)
}
catch {
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
catch {
"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'
}
Write-Error @MessageParams
}
}
default {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
# Check for an existing WinSCP Session var
"FTP" {
if ($Global:WinSCPSession.Opened) {
Remove-WinSCPSession -WinSCPSession $Global:WinSCPSession
}
else {
$MessageParams = @{
Message = "There is no open WinSCP Session"
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
# DataONTAP doesn't have a CmdLet `Disconnect-NcController`.
# So we go ahead and clear the CurrentNcController variable.
"NetAppFAS" {
try {
$MessageParams = @{
Message = "Setting {0} to `$null, which will disconnect NetAppFAS" -f $Global:CurrentNcController
ErrorAction = "Continue"
}
Write-Verbose @MessageParams
$Global:CurrentNcController = $null
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
"CiscoUcs" {
try {
Disconnect-Ucs -Ucs $RemoteHost
}
catch {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
default {
# Write a error message to the log.
$MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
}

View File

@ -0,0 +1,106 @@
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
#>
[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

@ -26,6 +26,18 @@
"Modules": [
"DataONTAP"
]
},
{
"Name": "CisServer",
"Modules": [
"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,43 @@
<?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>
<Label>Country</Label>
<ScriptBlock>$_.Subject.Country</ScriptBlock>
</ListItem>
<ListItem>
<Label>State</Label>
<ScriptBlock>$_.Subject.State</ScriptBlock>
</ListItem>
<ListItem>
<Label>City</Label>
<ScriptBlock>$_.Subject.City</ScriptBlock>
</ListItem>
<ListItem>
<Label>Organization</Label>
<ScriptBlock>$_.Subject.Organization</ScriptBlock>
</ListItem>
<ListItem>
<Label>OrganizationalUnitName</Label>
<ScriptBlock>$_.Subject.OrganizationalUnitName</ScriptBlock>
</ListItem>
<ListItem>
<Label>CommonName</Label>
<ScriptBlock>$_.Subject.CommonName</ScriptBlock>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@ -1,47 +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

@ -1,85 +0,0 @@
function Resolve-Dependency {
<#
.SYNOPSIS
Tests defined optional dependencies and returns the result as bool.
.DESCRIPTION
Use this function to test for optional modules. You can use it if you provide functions which needs special
modules but you don't want to make them required.
Place a file called Dependency.json in your module root dir. The default format is:
{
"Version": 0.1,
"Mandatory": {},
"Optional": [
{
"Name": "VMware",
"Modules": [
"VMware.VimAutomation.Core"
]
},
{
"Name": "CiscoUCS",
"Modules": []
}
]
}
.PARAMETER Name
Select the dependency item name you defined in the dependency.json.
.INPUTS
[None]
.OUTPUTS
[bool]
.EXAMPLE
If (-not (Resolve-Dependency -Name 'VMware')) {
Write-Error -Message ("Could not resolve the optional dependencies defined for {0}" -f 'VMware') -ErrorAction 'Stop'
}
.NOTES
File Name : ResolveDependency.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[OutputType([bool])]
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Name
)
begin {
$ModuleRootDir = $MyInvocation.MyCommand.Module.ModuleBase
$DepFilePath = Join-Path -Path $ModuleRootDir -ChildPath "Dependency.json"
if (Test-Path -Path $DepFilePath) {
$Dependency = Get-Content -Path $DepFilePath -Raw -Encoding UTF8 | ConvertFrom-Json
}
else {
Write-Warning ("Could not find the dependency file: {0}" -f $DepFilePath)
}
$res = @()
}
process {
$SelectedDependency = $Dependency.Optional | Where-Object {$_.Name -match $Name}
foreach ($Module in $SelectedDependency.Modules) {
$res += Test-Module -Name $Module
}
if ($res -contains $false) {
return $false
}
else {
return $true
}
}
end {
}
}

View File

@ -29,81 +29,92 @@ function Get-CredentialStoreItem {
.EXAMPLE
$myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.NOTES
File Name : Get-CredentialStoreItem.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType([System.Management.Automation.PSCredential])]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[CmdletBinding(DefaultParameterSetName = 'Private')]
[OutputType([PSCredential])]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $true, ParameterSetName = 'Private')]
[ValidateNotNullOrEmpty()]
[string]$RemoteHost,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $false, ParameterSetName = 'Private')]
[ValidateNotNullOrEmpty()]
[string]$Identifier,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[ValidateNotNullOrEmpty()]
[string]$Path
)
# First set a constand path for private CredentialStore mode.
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
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
}
}
}
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
process {
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
# Let`s first check if the given remote host exists as object property
if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -eq $CredentialName)) {
if ($CS.Type -eq "Private") {
$CSItem = [ordered]@{
User = $CS.$CredentialName.User
Password = ConvertTo-SecureString -String $CS.$CredentialName.Password
if (Test-CredentialStore -Shared -Path $Path) {
$CS = Get-CredentialStore -Shared -Path $Path
$CSMembers = Get-Member -InputObject $CS
# Let's first check if the given remote host exists as object property
if (($CSMembers.MemberType -eq 'NoteProperty') -and ($CSMembers.Name -contains $CredentialName)) {
if ($null -eq $CS.PfxCertificate) {
$Cert = Get-CSCertificate -Type $CS.Type -Thumbprint $CS.Thumbprint
}
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 {
$Key = Get-ChallengeFile
$CSItem = [ordered]@{
User = $CS.$CredentialName.User
Password = ConvertTo-SecureString -String $CS.$CredentialName.Password -Key $Key
$MsgParams = @{
ErrorAction = 'Stop'
Message = 'Could not find credentials for the given remote host: {0}' -f $RemoteHost
}
Write-Error @MsgParams
}
New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CSItem.User, $CSItem.Password
}
else {
$MsgParams = @{
ErrorAction = "Stop"
Message = "Could not find credentials for the given remote host: {0}" -f $RemoteHost
ErrorAction = 'Stop'
Message = 'The given credential store ({0}) does not exist!' -f $Path
}
Write-Error @MsgParams
}
}
else {
$MsgParams = @{
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
end {
}
}

View File

@ -0,0 +1,145 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingConvertToSecureStringWithPlainText',
'',
Justification = 'just used in pester tests.'
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSProvideCommentHelp',
'',
Justification = 'no need in internal pester helpers.'
)]
param ()
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
Describe "New-CredentialStoreItem" {
Context "Private Credential Store tests" {
It "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 "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"
$StoreItemParam = @{
Shared = $true
Path = $tmpCS
RemoteHost = $RemoteHost
Credential = $mycreds
identifier = 'Foo'
}
New-CredentialStoreItem @StoreItemParam
$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 } -ModuleName 'PSCredentialStore'
It "Missing CredentialStore should throw" {
{
New-CredentialStoreItem -Shared -Path '/tmp/missingStore.json' -RemoteHost 'notrelevant'
} | Should -Throw "The given credential store (/tmp/missingStore.json) does not exist!"
}
}
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

@ -21,6 +21,10 @@ function New-CredentialStoreItem {
.PARAMETER Credential
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
[None]
@ -28,108 +32,137 @@ function New-CredentialStoreItem {
[None]
.EXAMPLE
New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.NOTES
File Name : New-CredentialStoreItem.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
New-CredentialStoreItem -Path 'C:\TMP\mystore.json' -RemoteHost esx01.myside.local'
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[CmdletBinding(DefaultParameterSetName = 'Private')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions',
'',
Justification = 'Adds data into an existing object/file'
)]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $true, ParameterSetName = 'Private')]
[ValidateNotNullOrEmpty()]
[string]$RemoteHost,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $false, ParameterSetName = 'Private')]
[ValidateNotNullOrEmpty()]
[string]$Identifier,
[Parameter(Mandatory = $false)]
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[pscredential]$Credential,
[PSCredential]$Credential,
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[ValidateNotNullOrEmpty()]
[string]$Path
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared
)
# First set a constand path for private CredentialStore mode.
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
# 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"
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
}
Write-Error @MessageParams
}
# 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
elseif ($PSCmdlet.ParameterSetName -eq 'Shared') {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
else {
$encypted = ConvertFrom-SecureString -SecureString $Credential.Password
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
}
process {
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Shared -Path $Path)) {
$MessageParams = @{
Message = "The given host already exists. Nothing to do here."
Exception = [System.IO.FileNotFoundException]::new(
'The given credential store ({0}) does not exist!' -f $Path
)
ErrorAction = 'Stop'
}
Write-Warning @MessageParams
Write-Error @MessageParams
}
$CSContent = Get-CredentialStore -Shared -Path $Path
$CurrentDate = Get-Date -Format 'u'
if ($Identifier -ne '') {
$CredentialName = $RemoteHost = '{0}/{1}' -f $Identifier, $RemoteHost
}
else {
$CredentialHash = [ordered]@{
User = $Credential.UserName
Password = $encypted
Creation = $CurrentDate
$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
}
Add-Member -InputObject $CSContent -Name $CredentialName -MemberType NoteProperty -Value $CredentialHash
try {
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
else {
$Cert = Get-PfxCertificate -FilePath $CSContent.PfxCertificate -ErrorAction Stop
}
catch [System.Exception] {
if (Get-Member -InputObject $CSContent -Name $CredentialName -MemberType Properties) {
$MessageParams = @{
Message = "Couldn't add item into credential store!"
ErrorAction = "Stop"
Message = 'The given host already exists. Nothing to do here.'
}
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
)
)
}
$MemberParams = @{
InputObject = $CSContent
Name = $CredentialName
MemberType = 'NoteProperty'
Value = $CredentialHash
}
Add-Member @MemberParams
try {
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
}
catch {
$MessageParams = @{
Message = 'Could not add item into credential store!'
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
Write-Error @MessageParams
}
}
}
else {
$MessageParams = @{
Message = "Please Provide at least a valid user!"
ErrorAction = "Stop"
else {
$MessageParams = @{
Message = 'Please Provide at least a valid user!'
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
Write-Error @MessageParams
}
end {}
}

View File

@ -27,68 +27,89 @@ function Remove-CredentialStoreItem {
[None]
.EXAMPLE
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local"
.NOTES
File Name : Remove-CredentialStoreItem.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.EXAMPLE
Remove-CredentialStoreItem -Shared -RemoteHost "esx01.myside.local"
.LINK
https://github.com/OCram85/PSCredentialStore
.EXAMPLE
Remove-CredentialStoreItem -Shared -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.EXAMPLE
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local" -Identifier svc
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[CmdletBinding(DefaultParameterSetName = 'Private')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions',
'',
Justification = 'Removes data from existing store.'
)]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Private')]
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[string]$RemoteHost,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = 'Private')]
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[string]$Identifier,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[ValidateNotNullOrEmpty()]
[string]$Path
)
# First set a constand path for private CredentialStore mode.
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
# 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"
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
}
Write-Error @MessageParams
}
# 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."
elseif ($PSCmdlet.ParameterSetName -eq 'Shared') {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
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

@ -0,0 +1,130 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingConvertToSecureStringWithPlainText',
'',
Justification = 'just used in pester tests.'
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSProvideCommentHelp',
'',
Justification = 'no need in internal pester helpers.'
)]
param ()
BeforeAll {
$ManifestFile = (Get-Item -Path './src/*.psd1').FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path './src/Private/*.ps1' | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
# Backup existing credential stores
$VerbosePreference = 'Continue'
Write-Verbose -Message 'Backup private Credential Store...'
$CSPath = Get-DefaultCredentialStorePath
$BackupFile = '{0}.back' -f $CSPath
if (Test-Path -Path $CSPath) {
Move-Item -Path $CSPath -Destination $BackupFile
}
Write-Verbose -Message 'Backup shared CredentialStore...'
$CSShared = Get-DefaultCredentialStorePath -Shared
$BackupSharedFile = '{0}.back' -f $CSShared
if (Test-Path -Path $CSShared) {
Move-Item -Path $CSShared -Destination $BackupSharedFile
}
Write-Verbose -Message 'Remove old CredentialStore in Temp dir'
$CSTemp = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
if (Test-Path -Path $CSTemp) {
Remove-Item -Path $CSTemp
}
$VerbosePreference = 'SilentlyContinue'
}
Describe 'New-CredentialStoreItem' {
Context 'Private Credential Store tests' {
It 'Add entry to a private store.' {
# Create a fresh CredentialStore first
New-CredentialStore -Force
# Define the content of the CredentialStoreItem.
$RemoteHost = 'barfoo'
$UserName = 'MyUser'
$Password = 'fooobarysdfsfs' | ConvertTo-SecureString -AsPlainText -Force
# Form the CredentialObject.
$creds = [PSCredential]::new($UserName, $Password)
# Create the CredentialStoreItem.
New-CredentialStoreItem -RemoteHost $RemoteHost -Credential $creds
# Formulate an update to the CredentialStoreItem.
$ClearPassword = 'fooobaryadfafa'
$Password = $ClearPassword | ConvertTo-SecureString -AsPlainText -Force
$creds = [PSCredential]::new($UserName, $Password)
{
Set-CredentialStoreItem -RemoteHost $RemoteHost -Credential $creds
} | Should -Not -Throw
# Control the content of the CredentialStore.
$content = Get-CredentialStoreItem -RemoteHost $RemoteHost
$content.GetNetworkCredential().Password | Should -Be $ClearPassword
}
}
Context 'Shared Credential Store tests' {
It 'Add entry to a shared store.' {
# Create a fresh CredentialStore first
$tmpCS = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
New-CredentialStore -Path $tmpCS -Force -Shared
# Define the content of the CredentialStoreItem.
$RemoteHost = 'barfoo'
$UserName = 'MyUser'
$Password = 'fooobarysdfsfs' | ConvertTo-SecureString -AsPlainText -Force
# Form the CredentialObject.
$creds = [PSCredential]::new($UserName, $Password)
# Create the CredentialStoreItem.
New-CredentialStoreItem -RemoteHost $RemoteHost -Credential $creds -Path $tmpCS -Shared
# Formulate an update to the CredentialStoreItem.
$ClearPassword = 'fooobaryadfafa'
$Password = $ClearPassword | ConvertTo-SecureString -AsPlainText -Force
$creds = [PSCredential]::new($UserName, $Password)
{
Set-CredentialStoreItem -RemoteHost $RemoteHost -Credential $creds -Path $tmpCS -Shared
} | Should -Not -Throw
# Control the content of the CredentialStore.
$content = Get-CredentialStoreItem -RemoteHost $RemoteHost -Path $tmpCS -Shared
$content.GetNetworkCredential().Password | Should -Be $ClearPassword
}
}
}
AfterAll {
# Cleanup test stores and restore existing ones.
$VerbosePreference = 'Continue'
Write-Verbose -Message 'Restoring private CredentialStore'
If (Test-Path -Path $BackupFile) {
If (Test-Path -Path $CSPath) {
Remove-Item -Path $CSPath
Move-Item -Path $BackupFile -Destination $CSPath
}
}
Write-Verbose -Message 'Restoring shared CredentialStore'
If (Test-Path -Path $BackupSharedFile) {
If (Test-Path -Path $CSShared) {
Remove-Item -Path $CSShared
Move-Item -Path $BackupSharedFile -Destination $CSShared
}
}
$VerbosePreference = 'SilentlyContinue'
}

View File

@ -4,6 +4,7 @@ function Set-CredentialStoreItem {
Changes the credentials for the given remote host in the store.
.DESCRIPTION
Use this function to update your already stored RemoteHost items.
.PARAMETER Path
Define the store in which your given host entry already exists.
@ -12,13 +13,16 @@ function Set-CredentialStoreItem {
Specify the host you for which you would like to change the credentials.
.PARAMETER Identifier
Defaults to "". Specify a string, which separates two CredentialStoreItems for the
Defaults to ''. Specify a string, which separates two CredentialStoreItems for the
same hostname.
.PARAMETER Shared
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
.PARAMETER Credential
Provided the new credentials you want to update inside the RemoteHost item.
.INPUTS
[None]
@ -26,89 +30,143 @@ function Set-CredentialStoreItem {
[None]
.EXAMPLE
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
Set-CredentialStoreItem -Path 'C:\TMP\mystore.json' -RemoteHost 'esx01.myside.local'
.NOTES
File Name : Set-CredentialStoreItem.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
.EXAMPLE
Set-CredentialStoreItem -Path 'C:\TMP\mystore.json' -RemoteHost 'esx01.myside.local' -Identifier svc
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[CmdletBinding(DefaultParameterSetName = 'Private')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions',
'',
Justification = 'Updates existing credential object.'
)]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Private')]
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[string]$RemoteHost,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = 'Private')]
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[string]$Identifier,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[PSCredential]$Credential,
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[ValidateNotNullOrEmpty()]
[string]$Path
)
# First set a constant path for private CredentialStore mode.
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
# 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"
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
}
}
Write-Error @MessageParams
}
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore -Path $Path
process {
# Define the default splatting.
$DefaultSplatting = @{
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
# Check if the user passed -Shared. If he added -Shared, we'll pass it into the splatting
if ($PSBoundParameters.ContainsKey('Shared')) {
$DefaultSplatting.Add('Shared', $true)
}
else {
$encypted = ConvertFrom-SecureString -SecureString $Creds.Password
$DefaultSplatting.Add('Shared', $false)
}
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
# Now lets check the given CredentialStore.
if (-not(Test-CredentialStore @DefaultSplatting)) {
$MessageParams = @{
Message = ('The given CredentialStore ({0}) does no exist.' -f $Path)
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore @DefaultSplatting
# Get a formatted current date for the last update time of the Item.
$CurrentDate = Get-Date -Format 'u'
# Check if the user supplied an identifier. If so, we need to mangle the CredentialName, as that's where
# the identifier is actually added.
if ($Identifier -ne '') {
$CredentialName = $RemoteHost = '{0}/{1}' -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
# If the user didn't supply a CredentialObject, we need to prompt for it.
if (-not($Credential)) {
$Credential = Get-Credential -Message $CredentialName
}
# If the username isn't empty, we ca go ahead and update the entry.
if ($null -ne $Credential.UserName -and -not [string]::IsNullOrWhiteSpace($Credential.UserName)) {
# Check if the path to the PfxCertificate is stored in the CredentialStore. If so load the certificate.
# If not, load try loading the certificate from the Filepath of the CredentialStore.
if ($null -eq $CSContent.PfxCertificate) {
$Cert = Get-CSCertificate -Type $CSContent.Type -Thumbprint $CSContent.Thumbprint
}
else {
$Cert = Get-PfxCertificate -FilePath $CSContent.PfxCertificate -ErrorAction Stop
}
# Now locate the Item.
if (Get-Member -InputObject $CSContent -Name $CredentialName -MemberType Properties) {
# Get a random AES key for the entry.
$RSAKey = Get-RandomAESKey
$CSContent.$CredentialName.User = $Credential.UserName
$ConvertParams = @{
SecureString = $Credential.Password
Key = $RSAKey
}
# Now create a updated item containing the updated credentials.
$CSContent.$CredentialName.Password = ConvertFrom-SecureString @ConvertParams
$CSContent.$CredentialName.LastChange = $CurrentDate
$CSContent.$CredentialName.EncryptedKey = [Convert]::ToBase64String(
$Cert.PublicKey.Key.Encrypt(
$RSAKey,
[System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1
)
)
# Convert the CredentialStore back into JSON and save it to the file.
ConvertTo-Json -InputObject $CSContent -Depth 5 | Out-File -FilePath $Path -Encoding utf8
}
else {
Write-Warning -Message ('Unable to locate CredentialStoreItem for {0}' -f $CredentialName)
}
}
else {
$MessageParams = @{
Message = "The given CredentailStoreItem does not exist."
Message = 'Please Provide at least a valid user!'
ErrorAction = 'Stop'
}
Write-Warning @MessageParams
Write-Error @MessageParams
}
}
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
Checks if the given RemoteHost identifier combination exists in the credential store.
@ -7,6 +7,10 @@ function Test-CredentialStoreItem() {
Use this cmdlet for basic checks with a single item. Check the item first with this function before
you try to interact with it.
Breaking Change for `v1.1.0+`:
Test-CredentialStoreItem will return `$false` even if the store doesn't exist. We removed the terminating
error and replaced it with a warning message.
.PARAMETER Path
Define a custom credential store you try to read from. Without the `-Path` parameter
`Test-CredentialStoreItem` tries to read from the default private store.
@ -29,26 +33,19 @@ function Test-CredentialStoreItem() {
[None]
.EXAMPLE
If (Test-CredentialStoreItem -RemoteHost "Default") {
Get-CredentialStoreItem -RemoteHost "Default"
if (Test-CredentialStoreItem -RemoteHost 'Default') {
Get-CredentialStoreItem -RemoteHost 'Default'
}
Else {
Write-Warning ("The given Remote Host {0} does not exist in the credential Store!" -f $RemoteHost)
else {
Write-Warning ('The given Remote Host {0} does not exist in the credential Store!' -f $RemoteHost)
}
.NOTES
File Name : Test-CredentialStoreItem.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType([Boolean])]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[CmdletBinding(DefaultParameterSetName = 'Private')]
[OutputType([bool])]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[string]$Path = '{0}\PSCredentialStore\CredentialStore.json' -f $env:ProgramData,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
@ -58,36 +55,50 @@ function Test-CredentialStoreItem() {
[ValidateNotNullOrEmpty()]
[string]$Identifier,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[switch]$Shared
)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
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
}
}
}
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
process {
if ($Identifier -ne '') {
$CredentialName = $RemoteHost = '{0}/{1}' -f $Identifier, $RemoteHost
}
else {
$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 = @{
Message = 'The given credential store ({0}) does not exist!' -f $Path
}
Write-Warning @MsgParams
return $false
}
}
else {
$MsgParams = @{
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
}
end {}
}

11
src/ModuleRoot.psm1 Normal file
View File

@ -0,0 +1,11 @@
#region module-definition
#endregion module-definition
Set-Variable -Name "CSVersion" -Value "2.0.0" -Option Constant -Scope 'Script' -ErrorAction Stop
# Get all child items in the Script path and exclude the Deploy script (if present.)
$Functions = Get-ChildItem -Path $PSScriptRoot\*.ps1 -Recurse | Where-Object { $_.BaseName -notmatch '.Tests' }
foreach ($Item in $Functions) {
. $Item.FullName
}

View File

@ -1,51 +1,44 @@
#
# Module manifest for module 'PSCredentialStore'
#
# Generated by: OCram85
#
# Generated on: 27.07.2017
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'PSCredentialStore'
RootModule = 'ModuleRoot.psm1'
# Version number of this module.
# Do not touch the version number. It gets replaced in the build process.
ModuleVersion = '0.0.0.9999'
ModuleVersion = '0.0.9999'
# Supported PSEditions
# CompatiblePSEditions = @()
CompatiblePSEditions = 'Desktop', 'Core'
# ID used to uniquely identify this module
GUID = '6800e192-9df8-4e30-b253-eb2c799bbe84'
GUID = '6800e192-9df8-4e30-b253-eb2c799bbe84'
# Author of this module
Author = 'OCram85'
Author = 'OCram85'
# Company or vendor of this module
CompanyName = ''
CompanyName = ''
# Copyright statement for this module
Copyright = '(c) 2017 OCram85. All rights reserved.'
Copyright = '(c) OCram85. All rights reserved.'
# Description of the functionality provided by this module
Description = 'A simple credential manager to store and reuse multiple credential objecs'
Description = 'A simple cross-platform credential manager for PSCredential objects.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '4.0'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '5.1'
# Name of the Windows PowerShell host required by this module
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# Minimum version of the PowerShell host required by this module
# 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.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for
# the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
@ -64,37 +57,54 @@
# TypesToProcess = @()
# 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
# 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.
FunctionsToExport = @(
# Connection Group
# 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 = @(
# Certificate
'Get-CSCertificate',
'Import-CSCertificate',
'New-CSCertAttribute',
'New-CSCertificate',
'Test-CSCertificate',
'Use-CSCertificate',
# Pfx Certificate
# 'Get-CSPfxCertificate',
# 'Import-CSPfxCertificate',
# 'Test-CSPfxCertificate',
# Connection
'Connect-To',
'Disconnect-From',
# Item Group
'Test-CSConnection',
# Item
'Get-CredentialStoreItem',
'Set-CredentialStoreItem',
'New-CredentialStoreItem',
'Remove-CredentialStoreItem',
'Set-CredentialStoreItem',
'Test-CredentialStoreItem',
# Store Group
# Store
'Get-CredentialStore',
'New-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.
CmdletsToExport = @()
# 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 = @()
# 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.
AliasesToExport = @()
# 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 = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
@ -105,36 +115,70 @@
# List of all files packaged with this module
# 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.
PrivateData = @{
# 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 = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('CredentialStore',
'CredentialManager'
)
Tags = 'CredentialStore', 'CredentialManager'
# A URL to the license for this module.
LicenseUri = 'https://github.com/OCram85/PSCredentialStore/blob/master/LICENSE'
LicenseUri = 'https://gitea.ocram85.com/OCram85/PSCredentialStore/raw/branch/master/LICENSE'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/OCram85/PSCredentialStore'
ProjectUri = 'https://gitea.ocram85.com/OCram85/PSCredentialStore'
# A URL to an icon representing this module.
# IconUri = ''
IconUri = 'https://gitea.ocram85.com/OCram85/PSCredentialStore/raw/branch/master/assets/logo256.png'
# ReleaseNotes of this module
ReleaseNotes = 'This is a pre-release version!. Do not use in production!'
ReleaseNotes = 'See https://gitea.ocram85.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 = @(
@{
ModuleName = 'VMware.VimAutomation.Core'
ModuleVersion = '12.7.0.20091293'
},
@{
ModuleName = 'VMware.VimAutomation.Cis.Core'
ModuleVersion = '12.6.0.19601368'
},
@{
ModuleName = 'Cisco.UCS.Common'
ModuleVersion = '3.0.1.2'
},
@{
ModuleName = 'Cisco.UCSManager'
ModuleVersion = '3.0.1.2'
},
@{
ModuleName = 'WinSCP'
ModuleVersion = '5.17.8.1'
},
@{
ModuleName = 'NetApp.ONTAP'
ModuleVersion = '9.10.1.2111'
}
)
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
HelpInfoURI = 'https://github.com/OCram85/PSCredentialStore'
HelpInfoURI = 'https://gitea.ocram85.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 = ''
}

View File

@ -1,10 +0,0 @@
$Items = (Get-ChildItem -Path ("{0}\*.ps1" -f $PSScriptRoot ) -Recurse ).FullName | Where-Object {
$_ -notmatch "(Classes|Init)"
}
ForEach ($Item in $Items) {
# Write-Verbose ("dot sourcing file {0}" -f $Item)
. $Item
}
# Exports are now controlled by module manifest
# Export-ModuleMember -Function *

12
src/PSModule.Tests.ps1 Normal file
View File

@ -0,0 +1,12 @@
Describe 'Test module meta' {
Context 'Default tests' -Tag 'Default' {
It 'Test manifest file' {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Test-ModuleManifest -Path $ManifestFile | Should -Be $true
}
It 'Import Module' {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
{ Import-Module $ManifestFile } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,74 @@
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'
#>
[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,62 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
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,62 @@
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
#>
[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,20 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
Describe "Get-ModuleBase" {
Context "Basic syntax check" {
It "Test1: Should not throw" {
{ Get-ModuleBase } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,21 @@
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
#>
[CmdletBinding()]
[OutputType([string])]
param ()
begin {}
process {
return $MyInvocation.MyCommand.Module.ModuleBase
}
end {}
}

View File

@ -0,0 +1,26 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
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,36 @@
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
#>
[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 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
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,41 @@
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
#>
[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,108 @@
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')
#>
[CmdletBinding()]
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

@ -0,0 +1,25 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
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,81 @@
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'
#>
[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 {
# Script analyzer issue (unused var) workaround
$null = $Thumbprint
$Cert = $Store.Certificates | Where-Object { $_.Thumbprint -eq $Thumbprint }
if ($null -eq $Cert) {
return $false
}
else {
return $true
}
}
end {
$Store.Close()
}
}

View File

@ -0,0 +1,39 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
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

@ -32,26 +32,15 @@ function Test-Module {
.EXAMPLE
.\Test-Dependency -Name 'VMware.PowerCLI' -Type 'Module' -StopIfFails
.NOTES
File Name : Get-RandomKey.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[OutputType([bool])]
[CmdletBinding()]
param(
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(Mandatory = $false)]
[ValidateSet('Module', 'PSSnapin', 'Custom')]
[string]$Type = 'Module',
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$MessagePattern = @"
@ -60,45 +49,23 @@ Could not find the required {0} called {1}. Please install the required {0} to r
[Parameter(Mandatory = $false)]
[switch]$StopIfFails
)
begin {
}
begin {}
process {
$Message = $MessagePattern -f $Type, $Name
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-PSSnapin -Name $Name -Registered) {
return $true
}
else {
if ($StopIfFails) {
Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
return $false
}
}
}
'Custom' {
Throw 'Custom tests are not implemented yet!'
if (Get-Module -Name $Name -ListAvailable) {
return $true
}
else {
if ($StopIfFails) {
Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
}
return $false
}
}
end {
}
end {}
}

View File

@ -0,0 +1,45 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
Describe "Get-CredentialStore" {
Context "Basic logic tests" {
It "Read CS without params" {
if (! (Test-Path -Path (Get-DefaultCredentialStorePath)) ) {
{ New-CredentialStore -Force } | Should -Not -Throw
}
{ Get-CredentialStore } | Should -Not -Throw
}
It "Read Credential Store with testing data" {
$TestCredentialStore = './resources/cs/CredentialStore.json'
$TestPfxCert = './resources/cs/PSCredentialStore.pfx'
{
Use-CSCertificate -Shared -CredentialStore $TestCredentialStore -Path $TestPfxCert
} | Should -Not -Throw
{ Get-CredentialStore -Shared -Path $TestCredentialStore } | Should -Not -Throw
}
It "Test3: Not existing path should return false" {
{
Get-CredentialStore -Shared -Path './CredentialStore.json'
} | Should -Throw "Could not find the CredentialStore."
}
}
Context "Testing invalid json data" {
It "Should throw with invalid CredentialStore" {
$BrokenCS = './resources/cs/Broken_CS.json'
Write-Verbose -Message ('BrokenCS Path: {0}' -f $BrokenCS) -Verbose
{
Get-CredentialStore -Path -Shared $BrokenCS
} | Should -Throw
}
}
}

View File

@ -23,47 +23,57 @@ function Get-CredentialStore {
.EXAMPLE
$CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json"
.NOTES
File Name : Get-CredentialStore.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[CmdletBinding(DefaultParameterSetName = 'Private')]
[OutputType('PSCredentialStore.Store')]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path,
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[switch]$Shared
)
if ($PSCmdlet.ParameterSetName -eq 'Private') {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
begin {}
if (Test-CredentialStore -Path $Path) {
try {
$FileContent = Get-Content -Path $Path -Raw
ConvertFrom-Json $FileContent
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
}
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')
Write-Output $CS
}
catch [System.Exception] {
$MessageParams = @{
Message = 'Unknown CredentialStore format. Invalid JSON file.'
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
else {
$MessageParams = @{
Message = "Unknown CredentialStore format. Invalid JSON file."
ErrorAction = "Stop"
Message = 'Could not find the CredentialStore.'
ErrorAction = 'Stop'
}
Write-Error @MessageParams
}
}
else {
$MessageParams = @{
Message = "Could not find the CredentialStore."
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
end {}
}

View File

@ -0,0 +1,141 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
# Backup existing credential stores
$VerbosePreference = "Continue"
Write-Verbose "Backup private Credential Store..."
$CSPath = Get-DefaultCredentialStorePath
$BackupFile = "{0}.back" -f $CSPath
if (Test-Path -Path $CSPath) {
Move-Item -Path $CSPath -Destination $BackupFile
}
Write-Verbose "Backup shared CredentialStore..."
$CSShared = Get-DefaultCredentialStorePath -Shared
$BackupSharedFile = "{0}.back" -f $CSShared
if (Test-Path -Path $CSShared) {
Move-Item -Path $CSShared -Destination $BackupSharedFile
}
Write-Verbose "Remove old CredentialStore in Temp dir"
$CSTemp = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
if (Test-Path -Path $CSTemp) {
Remove-Item -Path $CSTemp
}
$VerbosePreference = "SilentlyContinue"
}
Describe "New-CredentialStore" {
Context "Private CS tests" {
It "Create new private CredentialStore" {
$pCS = Get-DefaultCredentialStorePath
{ New-CredentialStore -Confirm:$false -Force } | Should -Not -Throw
$result = Test-Path -Path $pCS
$CS = Get-Content -Path $pCS -Raw | ConvertFrom-Json
($result -eq $true) -and ($CS.Type -eq "Private") | Should -Be $true
}
It "Try to override private Store" {
{ New-CredentialStore -Confirm:$false } | Should -Throw
}
It "Reset existing Credential Store" {
$pCS = Get-DefaultCredentialStorePath
$now = Get-Date
$CS = Get-Content -Path $pCS -Raw | ConvertFrom-Json
$CSCreation = [DateTime]$CS.Created
New-CredentialStore -Confirm:$false -Force
$now -gt $csCreation | Should -Be $true
}
}
Context "Shared CS tests" {
It "Create a new Shared Credential Store" {
$sCS = Get-DefaultCredentialStorePath -Shared
{ New-CredentialStore -Confirm:$false -Shared } | Should -Not -Throw
Test-Path -Path $sCS | Should -Be $true
}
It "Try to override existing shared CS" {
{ New-CredentialStore -Shared -Confirm:$false } | Should -Throw
}
It "Reset shared CredentialStore" {
$sCS = Get-DefaultCredentialStorePath -Shared
$now = Get-Date
$CS = Get-Content -Path $sCS -Raw | ConvertFrom-Json
$CSCreation = [DateTime]$CS.Created
New-CredentialStore -Force -Shared -Confirm:$false
$now -gt $csCreation | Should -Be $true
}
}
Context "Custom Shared CS tests" {
It "Create new custom shared" {
$cCS = Join-Path -Path (Get-TempDir) -ChildPath "CredentialStore.json"
{ New-CredentialStore -Path $cCS -Shared -Confirm:$false -SkipPFXCertCreation } | Should -Not -Throw
}
It "Try to override exiting one" {
$cCS = Join-Path -Path (Get-TempDir) -ChildPath "CredentialStore.json"
{ New-CredentialStore -Path $cCS -Shared -Confirm:$false } | Should -Throw
}
It "Reset existing custom CredentialStore" {
$cCS = Join-Path -Path (Get-TempDir) -ChildPath "CredentialStore.json"
{ New-CredentialStore -Path $cCS -Shared -Force -Confirm:$false } | Should -Not -Throw
}
}
Context "Test exception handling" {
Mock Out-File { throw "foobar exception" }
It "JSON Conversion should fail and throw" {
{
New-CredentialStore -Path (
Join-Path -Path (Get-TempDir) -ChildPath '/dummy.json'
) -Shared -Confirm:$false
} | Should -Throw
}
}
Context "Tests for Windows certificate store" {
It "Create new private store and skip certificate linking" {
{ New-CredentialStore -UseCertStore -Force } | Should -Not -Throw
$CS = Get-CredentialStore
$CS.PfxCertificate | Should -Be $null
$CS.Thumbprint | Should -Not -Be $null
$res = Test-CSCertificate -Type Private
#Write-Verbose -Message ('res: {0}' -f $res) -Verbose
$res | Should -Be $true
}
It "Create new shared store and skipt certificate linking" {
{ New-CredentialStore -Shared -UseCertStore -Force } | Should -Not -Throw
$CS = Get-CredentialStore -Shared
$CS.PfxCertificate | Should -Be $null
$CS.Thumbprint | Should -Not -Be $null
$res = Test-CSCertificate -Type Shared
#Write-Verbose -Message ('res: {0}' -f $res) -Verbose
$res | Should -Be $true
}
}
}
AfterAll {
# Cleanup test stores and restore existing ones.
$VerbosePreference = "Continue"
Write-Verbose "Restoring private CredentialStore"
If (Test-Path -Path $BackupFile) {
If (Test-Path -Path $CSPath) {
Remove-Item -Path $CSPath
Move-Item -Path $BackupFile -Destination $CSPath
}
}
Write-Verbose "Restoring shared CredentialStore"
If (Test-Path -Path $BackupSharedFile) {
If (Test-Path -Path $CSShared) {
Remove-Item -Path $CSShared
Move-Item -Path $BackupSharedFile -Destination $CSShared
}
}
$VerbosePreference = "SilentlyContinue"
}

View File

@ -18,11 +18,21 @@ function New-CredentialStore {
.PARAMETER Force
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
[None]
.OUTPUTS
[None]
['PSCredentialStore.Store'] Returns the recently created CredentialStore object if the -PassThru parameter
was given.
.EXAMPLE
New-CredentialStore
@ -39,73 +49,199 @@ function New-CredentialStore {
.EXAMPLE
New-CredentialStore -Shared -Path "C:\TMP\CredentialStore.json"
# Creates a new shared CredentialStore in the given location.
.NOTES
File Name : New-CredentialStore.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'Private')]
[OutputType('PSCredentialStore.Store')]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[ValidateNotNullOrEmpty()]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[System.IO.FileInfo]$Path,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Force
[Parameter(Mandatory = $false, ParameterSetName = 'Private')]
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[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.
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
begin {
# Lets get the current Date in a human readable format.
$CurrentDate = Get-Date -Format 'u'
# Set latest Credential Store version
Set-Variable -Name "CSVersion" -Value "1.2.0" -Option Constant
# Set the CredentialStore path for private mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $Env:APPDATA
}
# Test if in the given store already a CredentialStore exists.
Write-Verbose "Test if there is already a credential store."
if ((Test-CredentialStore -Path $Path) -and ($Force -ne $true)) {
$MessageParam = @{
Message = "The given file already exists. Use the 'Force' switch to override the existing store."
ErrorAction = "Stop"
}
Write-Error @MessageParam
}
# We need to use the IDictionary to keep the property sorting in the object.
$ObjProperties = [ordered]@{
Version = $CSVersion
Creation = $CurrentDate
}
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
# test if the path input is a valid file path
if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Path')) {
if ($Path.Attributes -contains 'Directory') {
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.IO.InvalidDataException]::new(
'Please provide a full path containing the ' +
'credential store file name with the .json extension!'
)
}
Write-Error @ErrorParams
}
elseif ( ($null -eq $Path.Extension) -or ($Path.Extension -ne '.json')) {
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.IO.InvalidDataException]::new(
'Your provided path does not contain the required file extension .json!'
)
}
Write-Error @ErrorParams
}
}
}
else {
$ObjProperties.Type = "Private"
}
# Create a new object for easy conversion into a json file
$CredentialStoreObj = New-Object -TypeName psobject -Property $ObjProperties
try {
ConvertTo-Json -InputObject $CredentialStoreObj | Out-File -FilePath $Path
}
catch [System.Exception] {
$_.Exception | Format-List -Force | Out-String | Write-Error -ErrorAction Stop
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
}
}
end {}
}

View File

@ -0,0 +1,48 @@
BeforeAll {
$ManifestFile = (Get-Item -Path "./src/*.psd1").FullName
Import-Module $ManifestFile -Force
$PrivateFunctions = (Get-ChildItem -Path "./src/Private/*.ps1" | Where-Object {
$_.BaseName -notmatch '.Tests'
}
).FullName
foreach ( $func in $PrivateFunctions) {
. $func
}
}
Describe "Test-CredentialStore" {
Context "Basic logic tests" {
It "Should Not Throw" {
$TestCredentialStore = './resources/cs/CredentialStore.json'
{ Test-CredentialStore -Shared -Path $TestCredentialStore } | Should -Not -Throw
}
It "Read valid CredentialStore" {
$TestCredentialStore = './resources/cs/CredentialStore.json'
$res = Test-CredentialStore -Shared -Path $TestCredentialStore
$res | Should -Be $true
}
It "Read a broken CredentialStore" -Skip {
$BrokenCS = './resources/cs/Broken_CS.json'
$oWarningPreference = $WarningPreference
$WarningPreference = 'SilentlyContinue'
$res = Test-CredentialStore -Shared -Path $BrokenCS
$res | Should -Be $false
$WarningPreference = $oWarningPreference
}
It "Not existing path should return false" {
if ($isWindows -or ($PSVersionTable.PSVersion.Major -eq 5)) {
Test-CredentialStore -Shared -Path 'C:\foobar\CredentialStore.json' | Should -Be $false
}
elseif ($isWindows -or $IsMacOS) {
Test-CredentialStore -Shared -Path '/var/opt/foo.json' | Should -Be $false
}
}
It "testing private CredentialStore path" {
if (Test-Path -Path (Get-DefaultCredentialStorePath)) {
Remove-Item -Path (Get-DefaultCredentialStorePath)
}
Test-CredentialStore | Should -Be $false
}
}
}

View File

@ -14,48 +14,45 @@ function Test-CredentialStore {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems.
.NOTES
File Name : Test-CredentialStore.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
.EXAMPLE
Test-CredentialStore -eq $true
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[CmdletBinding(DefaultParameterSetName = 'Private')]
[OutputType([bool])]
param (
[Parameter(Mandatory = $false, ParameterSetName = 'Shared')]
[string]$Path,
[Parameter(Mandatory = $true, ParameterSetName = 'Shared')]
[switch]$Shared
)
begin {}
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $Env:APPDATA
}
# Set latest Credential Store version
Set-Variable -Name "CSVersion" -Value "1.2.0" -Option Constant
if (Test-Path $Path) {
Write-Verbose "CredentialStore in given path found."
# 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
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
}
catch {
Write-Warning "Could not read or convert the given CredentialStore."
Return $False
elseif ($PSCmdlet.ParameterSetName -eq 'Shared') {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$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.'
Write-Output $true
}
else {
Write-Verbose 'The given CredentialStore does not exist!'
Write-Output $false
}
}
Else {
Write-Verbose "The given CredentialStore does not exist!"
Return $False
}
end {}
}

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

Binary file not shown.

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