manage-local-admin-password

Форк
0
/
password-auto-rotate.ps1 
186 строк · 4.9 Кб
1
param (
2
    # Адрес сервера Vault в формате https://vault.acme.corp
3
    [Parameter(Mandatory = $True)]
4
    [string]$VaultAddr,
5
    [Parameter(Mandatory = $True)]
6
    [string]$RoleID,
7
    [Parameter(Mandatory = $True)]
8
    [string]$SecretID,
9
    [Parameter(Mandatory = $True)]
10
    [string]$PasswordPolicyName,
11
    [Parameter(Mandatory = $True)]
12
    [string]$SecretsStoreName,
13
    [Parameter(Mandatory = $True)]
14
    [string]$Username,
15
    [Parameter()]
16
    [string]$SecretsBasePath = "",
17
    [Parameter()]
18
    [string]$Hostname = $env:computername.ToLower()
19

20
)
21

22
$LOG_FILE = 'c:\windows\debug\password-auto-rotate.log'
23
$AppRoleLoginUri = "$VaultAddr/v1/auth/approle/login"
24
$GetPasswordUri = "$VaultAddr/v1/sys/policies/password/$PasswordPolicyName/generate"
25
$SecretUri1 = "$VaultAddr/v1/$SecretsStoreName/data/$Hostname/$Username"
26
$SecretUri2 = "$VaultAddr/v1/$SecretsStoreName/data/$SecretsBasePath/$Hostname/$Username"
27

28
if (-not [System.Diagnostics.EventLog]::SourceExists("PasswordAutoRotate")) {
29
    New-EventLog -LogName Application -Source PasswordAutoRotate
30
}
31

32
function WriteLog {
33
    [CmdletBinding()]
34
    Param(
35
        [Parameter(Mandatory = $False)]
36
        [ValidateSet("INFO", "WARN", "ERROR", "FATAL", "DEBUG")]
37
        [String]
38
        $Level = "INFO",
39

40
        [Parameter(Mandatory = $True)]
41
        [string]
42
        $Message
43
    )
44
    $DateTime = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
45
    $LogMessage = "$Datetime $Level $Message"
46
    Add-content $LOG_FILE -value $LogMessage
47
}
48

49
function WriteEventLog {
50
    [CmdletBinding()]
51
    Param(
52
        [Parameter(Mandatory = $False)]
53
        [ValidateSet("INFO", "WARN", "ERROR")]
54
        [String]
55
        $Level = "INFO",
56

57
        [Parameter(Mandatory = $True)]
58
        [string]
59
        $Message
60
    )
61
    $typ = $null 
62
    switch ($Level) {
63
        "INFO" { $typ = "Information" }
64
        "WARN" { $typ = "Warning" }
65
        "ERROR" { $typ = "Error" }
66
    }
67
    Write-EventLog -LogName "Application" -Source "PasswordAutoRotate" `
68
        -EventID 1 -EntryType $typ -Message $Message
69
}
70

71
if (-not (Get-LocalUser $Username)) {
72
    $msg = "User with $Username does not exists"
73
    WriteLog ERROR  $msg
74
    WriteEventLog ERROR  $msg
75
    throw "User with $Username does not exists"
76
}
77

78
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
79
# Allow the use of self-signed SSL certificates.
80
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
81
$msg = "Started password update for user $Username"
82
WriteEventLog INFO $msg 
83
WriteLog INFO $msg 
84

85
$data = @{
86
    "role_id"   = $RoleID
87
    "secret_id" = $SecretID
88
}
89
$body = $data | ConvertTo-Json
90

91
# get vault token
92
try {
93
    $resp = Invoke-RestMethod -Method POST -ContentType "application/json" `
94
        -Body $body -Uri $AppRoleLoginUri
95
}
96
catch {
97
    $s = "Error getting vault token. Request uri=$AppRoleLoginUri. Response body: $resp"
98
    WriteLog ERROR $s
99
    WriteEventLog ERROR $s
100
    throw $_
101
}
102

103
$vaultAccessToken = $resp.auth.client_token
104
if (-not $vaultAccessToken) {
105
    $s = "Can not get Vault access token from response"
106
    WriteLog ERROR $s
107
    $msg = $resp | ConvertTo-Json
108
    WriteLog ERROR "Response data $msg"
109
    WriteEventLog ERROR $s
110
    throw $s
111
}
112

113
$headers = @{
114
    'Content-Type'  = 'application/json'
115
    'X-Vault-Token' = $vaultAccessToken
116
}
117
# get new password
118
$resp = $null
119
try {
120
    $resp = Invoke-RestMethod -Method Get `
121
        -Headers $headers -Uri $GetPasswordUri
122
}
123
catch {
124
    $s = "Can not get new password from vault. uri: $GetPasswordUri"
125
    $msg = $resp | ConvertTo-Json
126
    WriteEventLog ERROR $s
127
    WriteLog ERROR $s
128
    WriteLog ERROR $_
129
    WriteLog INFO $msg
130
    throw $_
131
}
132
$newPwd = $resp.data.password
133

134
if (-not $newPwd) {
135
    $s = "Can not get new password from Vault's response"
136
    WriteLog ERROR $s
137
    $msg = $resp | ConvertTo-Json
138
    WriteLog ERROR "Response data $msg"
139
    WriteEventLog ERROR $s
140
    throw $s
141
}
142
# write new pwd to Vault
143
$uri = $null
144
if ($SecretsBasePath -eq "") {
145
    $uri = $SecretUri1
146
}
147
else {
148
    $uri = $SecretUri2
149
}
150

151
$data = @{
152
    "data" = @{
153
        "username" = $Username
154
        "password" = $newPwd
155
    }
156
}
157
$body = $data | ConvertTo-Json
158
$resp = $null
159
try {
160
    $resp = Invoke-RestMethod -Method Post `
161
        -Headers $headers -Uri $uri -Body $body
162
}
163
catch {
164
    $s = "Can save new password to vault. uri: $uri"
165
    WriteEventLog ERROR $s
166
    WriteLog ERROR $s
167
    WriteLog ERROR $_
168
    throw $_
169
}
170

171
# update pwd 
172
try {
173
    $SecurePwd = ConvertTo-SecureString $newPwd -AsPlainText -Force
174
    $UserAccount = Get-LocalUser -name $Username
175
    $UserAccount | Set-LocalUser -Password $SecurePwd
176
    $msg = "Password for user $Username was stored in Vault and updated locally."
177
    WriteLog INFO  $msg
178
    WriteEventLog INFO $msg
179
}
180
catch {
181
    $msg = "Password for user $Username was stored in Vault but *not* updated locally."
182
    WriteEventLog ERROR $msg
183
    WriteLog ERROR $msg
184
    WriteLog ERROR $_
185
    throw $_
186
}
187

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.