-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathwindows_auth_go_sample.go
199 lines (175 loc) · 5.07 KB
/
windows_auth_go_sample.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"strings"
"time"
daisyCompute "github.com/GoogleCloudPlatform/compute-image-tools/daisy/compute"
"google.golang.org/api/compute/v1"
)
var (
instance = flag.String("instance", "", "instance to reset password on")
zone = flag.String("zone", "", "zone instance is in")
project = flag.String("project", "", "project instance is in")
user = flag.String("user", "", "user to reset password for")
)
func getInstanceMetadata(client daisyCompute.Client, i, z, p string) (*compute.Metadata, error) {
ins, err := client.GetInstance(p, z, i)
if err != nil {
return nil, fmt.Errorf("error getting instance: %v", err)
}
return ins.Metadata, nil
}
type windowsKeyJSON struct {
ExpireOn string
Exponent string
Modulus string
UserName string
}
func generateKey(priv *rsa.PublicKey, u string) (*windowsKeyJSON, error) {
bs := make([]byte, 4)
binary.BigEndian.PutUint32(bs, uint32(priv.E))
return &windowsKeyJSON{
ExpireOn: time.Now().Add(5 * time.Minute).Format(time.RFC3339),
// This is different than what the other tools produce,
// AQAB vs AQABAA==, both are decoded as 65537.
Exponent: base64.StdEncoding.EncodeToString(bs),
Modulus: base64.StdEncoding.EncodeToString(priv.N.Bytes()),
UserName: u,
}, nil
}
type credsJSON struct {
ErrorMessage string `json:"errorMessage,omitempty"`
EncryptedPassword string `json:"encryptedPassword,omitempty"`
Modulus string `json:"modulus,omitempty"`
}
func getEncryptedPassword(client daisyCompute.Client, i, z, p, mod string) (string, error) {
out, err := client.GetSerialPortOutput(p, z, i, 4, 0)
if err != nil {
return "", err
}
for _, line := range strings.Split(out.Contents, "\n") {
var creds credsJSON
if err := json.Unmarshal([]byte(line), &creds); err != nil {
continue
}
if creds.Modulus == mod {
if creds.ErrorMessage != "" {
return "", fmt.Errorf("error from agent: %s", creds.ErrorMessage)
}
return creds.EncryptedPassword, nil
}
}
return "", errors.New("password not found in serial output")
}
func decryptPassword(priv *rsa.PrivateKey, ep string) (string, error) {
bp, err := base64.StdEncoding.DecodeString(ep)
if err != nil {
return "", fmt.Errorf("error decoding password: %v", err)
}
pwd, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, priv, bp, nil)
if err != nil {
return "", fmt.Errorf("error decrypting password: %v", err)
}
return string(pwd), nil
}
func resetPassword(client daisyCompute.Client, i, z, p, u string) (string, error) {
md, err := getInstanceMetadata(client, *instance, *zone, *project)
if err != nil {
return "", fmt.Errorf("error getting instance metadata: %v", err)
}
fmt.Println("Generating public/private key pair")
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", err
}
winKey, err := generateKey(&key.PublicKey, u)
if err != nil {
return "", err
}
data, err := json.Marshal(winKey)
if err != nil {
return "", err
}
winKeys := string(data)
var found bool
for _, mdi := range md.Items {
if mdi.Key == "windows-keys" {
val := fmt.Sprintf("%s\n%s", *mdi.Value, winKeys)
mdi.Value = &val
found = true
break
}
}
if !found {
md.Items = append(md.Items, &compute.MetadataItems{Key: "windows-keys", Value: &winKeys})
}
fmt.Println("Setting new 'windows-keys' metadata")
if err := client.SetInstanceMetadata(p, z, i, md); err != nil {
return "", err
}
fmt.Println("Fetching encrypted password")
var trys int
var ep string
for {
time.Sleep(1 * time.Second)
ep, err = getEncryptedPassword(client, i, z, p, winKey.Modulus)
if err == nil {
break
}
if trys > 10 {
return "", err
}
trys++
}
fmt.Println("Decrypting password")
return decryptPassword(key, ep)
}
func main() {
flag.Parse()
if *instance == "" {
log.Fatal("-instance flag required")
}
if *zone == "" {
log.Fatal("-zone flag required")
}
if *project == "" {
log.Fatal("-project flag required")
}
if *user == "" {
log.Fatal("-user flag required")
}
ctx := context.Background()
client, err := daisyCompute.NewClient(ctx)
if err != nil {
log.Fatalf("Error creating compute service: %v", err)
}
fmt.Printf("Resetting password on instance %q for user %q\n", *instance, *user)
pw, err := resetPassword(client, *instance, *zone, *project, *user)
if err != nil {
log.Fatal(err)
}
fmt.Printf("- Username: %s\n- Password: %s\n", *user, pw)
}