-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorker.cs
79 lines (65 loc) · 2.81 KB
/
Worker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Pass2Vault
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private string secretName = Dns.GetHostName();
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Inspecting secrets at: {time}", DateTimeOffset.Now);
// <authenticate>
var kvUri = "https://" + Environment.GetEnvironmentVariable("AZURE_VAULT_NAME") + ".vault.azure.net";
var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
// </authenticate>
var secretValue = passworder.GetRandomAlphanumericString(48);
KeyVaultSecret superSecret = client.GetSecret(secretName);
if (superSecret.Properties.ExpiresOn.HasValue)
{
_logger.LogDebug("Secret is valid and will expire");
}
else {
_logger.LogDebug("Secret is not set to expire!");
}
if (superSecret.Properties.ExpiresOn.GetValueOrDefault() > DateTimeOffset.Now)
{
_logger.LogDebug($"Secret is still valid and Expires at: {superSecret.Properties.ExpiresOn.GetValueOrDefault()}");
}
if (superSecret.Properties.ExpiresOn.HasValue && superSecret.Properties.ExpiresOn.GetValueOrDefault() < DateTimeOffset.Now)
{
// Create a new secret.
_logger.LogDebug("Creating new Secret");
KeyVaultSecret newSuperSecret = new KeyVaultSecret(secretName, secretValue);
newSuperSecret.Properties.ExpiresOn = DateTimeOffset.Now.AddHours(8);
client.SetSecret(newSuperSecret);
try
{
// Change the current password.
Netadpi32.ChangePassword("sysadmin",null,superSecret.Value,newSuperSecret.Value);
}
catch
{
// Disable the newly created secret.
_logger.LogInformation("FUUUUCCCCCK");
}
// Delete old Secret??????
// Maybe disable Secret?
}
await Task.Delay(7200000, stoppingToken);
}
}
}
}