-
Notifications
You must be signed in to change notification settings - Fork 99
/
repository_resource.go
333 lines (291 loc) · 10.8 KB
/
repository_resource.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright 2020 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 config
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/GoogleCloudPlatform/osconfig/agentconfig"
"github.com/GoogleCloudPlatform/osconfig/clog"
"github.com/GoogleCloudPlatform/osconfig/packages"
"github.com/GoogleCloudPlatform/osconfig/util"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1"
)
const aptGPGDir = "/etc/apt/trusted.gpg.d"
type repositoryResource struct {
*agentendpointpb.OSPolicy_Resource_RepositoryResource
managedRepository ManagedRepository
}
// AptRepository describes an apt repository resource.
type AptRepository struct {
RepositoryResource *agentendpointpb.OSPolicy_Resource_RepositoryResource_AptRepository
GpgFilePath string
GpgChecksum string
GpgFileContents []byte
}
// GooGetRepository describes an googet repository resource.
type GooGetRepository struct {
RepositoryResource *agentendpointpb.OSPolicy_Resource_RepositoryResource_GooRepository
}
// YumRepository describes an yum repository resource.
type YumRepository struct {
RepositoryResource *agentendpointpb.OSPolicy_Resource_RepositoryResource_YumRepository
}
// ZypperRepository describes an zypper repository resource.
type ZypperRepository struct {
RepositoryResource *agentendpointpb.OSPolicy_Resource_RepositoryResource_ZypperRepository
}
// ManagedRepository is the repository that this RepositoryResource manages.
type ManagedRepository struct {
Apt *AptRepository
GooGet *GooGetRepository
Yum *YumRepository
Zypper *ZypperRepository
RepoFilePath string
RepoChecksum string
RepoFileContents []byte
}
func aptRepoContents(repo *agentendpointpb.OSPolicy_Resource_RepositoryResource_AptRepository) []byte {
var debArchiveTypeMap = map[agentendpointpb.OSPolicy_Resource_RepositoryResource_AptRepository_ArchiveType]string{
agentendpointpb.OSPolicy_Resource_RepositoryResource_AptRepository_DEB: "deb",
agentendpointpb.OSPolicy_Resource_RepositoryResource_AptRepository_DEB_SRC: "deb-src",
}
/*
# Repo file managed by Google OSConfig agent
deb http://repo1-url/ repo main
*/
var buf bytes.Buffer
buf.WriteString("# Repo file managed by Google OSConfig agent\n")
archiveType, ok := debArchiveTypeMap[repo.GetArchiveType()]
if !ok {
archiveType = "deb"
}
line := fmt.Sprintf("%s %s %s", archiveType, repo.GetUri(), repo.GetDistribution())
for _, c := range repo.GetComponents() {
line = fmt.Sprintf("%s %s", line, c)
}
buf.WriteString(line + "\n")
return buf.Bytes()
}
func googetRepoContents(repo *agentendpointpb.OSPolicy_Resource_RepositoryResource_GooRepository) []byte {
/*
# Repo file managed by Google OSConfig agent
- name: repo1-name
url: https://repo1-url
*/
var buf bytes.Buffer
buf.WriteString("# Repo file managed by Google OSConfig agent\n")
buf.WriteString(fmt.Sprintf("- name: %s\n", repo.Name))
buf.WriteString(fmt.Sprintf(" url: %s\n", repo.Url))
return buf.Bytes()
}
func yumRepoContents(repo *agentendpointpb.OSPolicy_Resource_RepositoryResource_YumRepository) []byte {
/*
# Repo file managed by Google OSConfig agent
[Id]
name=DisplayName
baseurl=https://repo-url
enabled=1
gpgcheck=1
gpgkey=http://repo-url/gpg1
http://repo-url/gpg2
*/
var buf bytes.Buffer
buf.WriteString("# Repo file managed by Google OSConfig agent\n")
buf.WriteString(fmt.Sprintf("[%s]\n", repo.Id))
if repo.DisplayName == "" {
buf.WriteString(fmt.Sprintf("name=%s\n", repo.Id))
} else {
buf.WriteString(fmt.Sprintf("name=%s\n", repo.DisplayName))
}
buf.WriteString(fmt.Sprintf("baseurl=%s\n", repo.BaseUrl))
buf.WriteString("enabled=1\ngpgcheck=1\n")
if len(repo.GpgKeys) > 0 {
buf.WriteString(fmt.Sprintf("gpgkey=%s\n", repo.GpgKeys[0]))
for _, k := range repo.GpgKeys[1:] {
buf.WriteString(fmt.Sprintf(" %s\n", k))
}
}
return buf.Bytes()
}
func zypperRepoContents(repo *agentendpointpb.OSPolicy_Resource_RepositoryResource_ZypperRepository) []byte {
/*
# Repo file managed by Google OSConfig agent
[Id]
name=DisplayName
baseurl=https://repo-url
enabled=1
gpgkey=https://repo-url/gpg1
https://repo-url/gpg2
*/
var buf bytes.Buffer
buf.WriteString("# Repo file managed by Google OSConfig agent\n")
buf.WriteString(fmt.Sprintf("[%s]\n", repo.Id))
if repo.DisplayName == "" {
buf.WriteString(fmt.Sprintf("name=%s\n", repo.Id))
} else {
buf.WriteString(fmt.Sprintf("name=%s\n", repo.DisplayName))
}
buf.WriteString(fmt.Sprintf("baseurl=%s\n", repo.BaseUrl))
buf.WriteString("enabled=1\n")
if len(repo.GpgKeys) > 0 {
buf.WriteString(fmt.Sprintf("gpgkey=%s\n", repo.GpgKeys[0]))
for _, k := range repo.GpgKeys[1:] {
buf.WriteString(fmt.Sprintf(" %s\n", k))
}
}
return buf.Bytes()
}
func serializeGPGKeyEntity(entityList openpgp.EntityList) ([]byte, error) {
var buf bytes.Buffer
for _, entity := range entityList {
if err := entity.Serialize(&buf); err != nil {
return nil, fmt.Errorf("error serializing gpg key: %v", err)
}
}
return buf.Bytes(), nil
}
func isArmoredGPGKey(keyData []byte) bool {
var buf bytes.Buffer
tee := io.TeeReader(bytes.NewReader(keyData), &buf)
// Try decoding as armored
decodedBlock, err := armor.Decode(tee)
if err == nil && decodedBlock != nil {
return true
}
return false
}
func fetchGPGKey(key string) (openpgp.EntityList, error) {
resp, err := http.Get(key)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.ContentLength > 1024*1024 {
return nil, fmt.Errorf("key size of %d too large", resp.ContentLength)
}
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("can not read response body for key %s, err: %v", key, err)
}
if isArmoredGPGKey(responseBody) {
return openpgp.ReadArmoredKeyRing(bytes.NewBuffer(responseBody))
}
return openpgp.ReadKeyRing(bytes.NewReader(responseBody))
}
func (r *repositoryResource) validate(ctx context.Context) (*ManagedResources, error) {
var repoFormat string
switch r.GetRepository().(type) {
case *agentendpointpb.OSPolicy_Resource_RepositoryResource_Apt:
if !packages.AptExists {
return nil, errors.New("cannot manage Apt repository because apt-get does not exist on the system")
}
gpgkey := r.GetApt().GetGpgKey()
r.managedRepository.Apt = &AptRepository{RepositoryResource: r.GetApt()}
r.managedRepository.RepoFileContents = aptRepoContents(r.GetApt())
repoFormat = agentconfig.AptRepoFormat()
if gpgkey != "" {
entityList, err := fetchGPGKey(gpgkey)
if err != nil {
return nil, fmt.Errorf("error fetching apt gpg key %q: %v", gpgkey, err)
}
keyContents, err := serializeGPGKeyEntity(entityList)
if err != nil {
return nil, fmt.Errorf("error fetching apt gpg key %q: %v", gpgkey, err)
}
r.managedRepository.Apt.GpgFileContents = keyContents
r.managedRepository.Apt.GpgChecksum = checksum(bytes.NewReader(keyContents))
r.managedRepository.Apt.GpgFilePath = filepath.Join(aptGPGDir, "osconfig_added_"+r.managedRepository.Apt.GpgChecksum+".gpg")
}
case *agentendpointpb.OSPolicy_Resource_RepositoryResource_Goo:
if !packages.GooGetExists {
return nil, errors.New("cannot manage googet repository because googet does not exist on the system")
}
r.managedRepository.GooGet = &GooGetRepository{RepositoryResource: r.GetGoo()}
r.managedRepository.RepoFileContents = googetRepoContents(r.GetGoo())
repoFormat = agentconfig.GooGetRepoFormat()
case *agentendpointpb.OSPolicy_Resource_RepositoryResource_Yum:
if !packages.YumExists {
return nil, errors.New("cannot manage yum repository because yum does not exist on the system")
}
r.managedRepository.Yum = &YumRepository{RepositoryResource: r.GetYum()}
r.managedRepository.RepoFileContents = yumRepoContents(r.GetYum())
repoFormat = agentconfig.YumRepoFormat()
case *agentendpointpb.OSPolicy_Resource_RepositoryResource_Zypper:
if !packages.ZypperExists {
return nil, errors.New("cannot manage zypper repository because zypper does not exist on the system")
}
r.managedRepository.Zypper = &ZypperRepository{RepositoryResource: r.GetZypper()}
r.managedRepository.RepoFileContents = zypperRepoContents(r.GetZypper())
repoFormat = agentconfig.ZypperRepoFormat()
default:
return nil, fmt.Errorf("Repository field not set or references unknown repository type: %v", r.GetRepository())
}
r.managedRepository.RepoChecksum = checksum(bytes.NewReader(r.managedRepository.RepoFileContents))
r.managedRepository.RepoFilePath = fmt.Sprintf(repoFormat, r.managedRepository.RepoChecksum[:10])
return &ManagedResources{Repositories: []ManagedRepository{r.managedRepository}}, nil
}
func contentsMatch(path, chksum string) (bool, error) {
file, err := os.OpenFile(path, os.O_RDONLY, 0644)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
defer file.Close()
return chksum == checksum(file), nil
}
func (r *repositoryResource) checkState(ctx context.Context) (inDesiredState bool, err error) {
// Check APT gpg key if applicable.
if r.managedRepository.Apt != nil && r.managedRepository.Apt.GpgFileContents != nil {
match, err := contentsMatch(r.managedRepository.Apt.GpgFilePath, r.managedRepository.Apt.GpgChecksum)
if err != nil {
return false, err
}
if !match {
return false, nil
}
}
return contentsMatch(r.managedRepository.RepoFilePath, r.managedRepository.RepoChecksum)
}
func (r *repositoryResource) enforceState(ctx context.Context) (inDesiredState bool, err error) {
clog.Infof(ctx, "Enforcing repo %s.", r.managedRepository.RepoFilePath)
// Set APT gpg key if applicable.
if r.managedRepository.Apt != nil && r.managedRepository.Apt.GpgFileContents != nil {
if err := ioutil.WriteFile(r.managedRepository.Apt.GpgFilePath, r.managedRepository.Apt.GpgFileContents, 0644); err != nil {
return false, err
}
}
if err := os.MkdirAll(filepath.Dir(r.managedRepository.RepoFilePath), 0755); err != nil {
return false, err
}
if err := util.AtomicWrite(r.managedRepository.RepoFilePath, r.managedRepository.RepoFileContents, 0644); err != nil {
return false, err
}
return true, nil
}
func (r *repositoryResource) populateOutput(rCompliance *agentendpointpb.OSPolicyResourceCompliance) {
}
func (r *repositoryResource) cleanup(ctx context.Context) error {
return nil
}