This repository has been archived by the owner on Sep 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 235
/
manifest.go
450 lines (410 loc) · 11.9 KB
/
manifest.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Contributor: Aaron Meihm ameihm@mozilla.com [:alm]
package mig /* import "github.com/mozilla/mig" */
// This file contains structures and functions related to the handling of
// manifests and state bundles by the MIG loader and API.
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"github.com/mozilla/mig/pgp"
"os"
"path"
"runtime"
"time"
)
// ManifestRecord describes a manifest record stored within the MIG database
type ManifestRecord struct {
ID float64 `json:"id"` // Manifest record ID
Name string `json:"name"` // The name of the manifest record
Content string `json:"content,omitempty"` // Full data contents of record
Timestamp time.Time `json:"timestamp"` // Record timestamp
Status string `json:"status"` // Record status
Target string `json:"target"` // Targetting parameters for record
Signatures []string `json:"signatures"` // Signatures applied to the record
}
// Validate validates an existing manifest record
func (m *ManifestRecord) Validate() (err error) {
if m.Name == "" {
return fmt.Errorf("manifest has invalid name")
}
if m.Target == "" {
return fmt.Errorf("manifest has invalid target")
}
if m.Status != "staged" && m.Status != "active" && m.Status != "disabled" {
return fmt.Errorf("manifest has invalid status")
}
// Attempt to convert it to a response as part of validation
_, err = m.ManifestResponse()
if err != nil {
return
}
return
}
// Sign will sign a manifest record using the indicated key ID
func (m *ManifestRecord) Sign(keyid string, secring io.Reader) (sig string, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("Sign() -> %v", e)
}
}()
// Convert the record into entry format, and strip existing signatures
// before signing.
me, err := m.ManifestResponse()
if err != nil {
panic(err)
}
me.Signatures = make([]string, 0)
buf, err := json.Marshal(me)
if err != nil {
panic(err)
}
sig, err = pgp.Sign(string(buf), keyid, secring)
if err != nil {
panic(err)
}
return
}
// ManifestResponse converts a manifest record into a manifest response
func (m *ManifestRecord) ManifestResponse() (ManifestResponse, error) {
ret := ManifestResponse{}
if len(m.Content) == 0 {
return ret, fmt.Errorf("manifest record has no content")
}
buf := bytes.NewBufferString(m.Content)
b64r := base64.NewDecoder(base64.StdEncoding, buf)
gzr, err := gzip.NewReader(b64r)
if err != nil {
return ret, err
}
tr := tar.NewReader(gzr)
for {
h, err := tr.Next()
if err != nil {
if err == io.EOF {
break
}
return ret, err
}
if h.Typeflag != tar.TypeReg {
continue
}
hash := sha256.New()
rbuf := make([]byte, 4096)
for {
n, err := tr.Read(rbuf)
if err != nil {
if err == io.EOF {
break
}
return ret, err
}
if n > 0 {
hash.Write(rbuf[:n])
}
}
_, entname := path.Split(h.Name)
newEntry := ManifestEntry{}
newEntry.Name = entname
newEntry.SHA256 = fmt.Sprintf("%x", hash.Sum(nil))
ret.Entries = append(ret.Entries, newEntry)
}
ret.Signatures = m.Signatures
return ret, nil
}
// ManifestObject returns the requested file object as a gzip compressed byte slice
// from the manifest record
func (m *ManifestRecord) ManifestObject(obj string) ([]byte, error) {
var bufw bytes.Buffer
var ret []byte
bufr := bytes.NewBufferString(m.Content)
b64r := base64.NewDecoder(base64.StdEncoding, bufr)
gzr, err := gzip.NewReader(b64r)
if err != nil {
return ret, err
}
tr := tar.NewReader(gzr)
found := false
for {
h, err := tr.Next()
if err != nil {
if err == io.EOF {
break
}
return ret, err
}
if h.Typeflag != tar.TypeReg {
continue
}
_, thisf := path.Split(h.Name)
if thisf != obj {
continue
}
found = true
gzw := gzip.NewWriter(&bufw)
buftemp := make([]byte, 4096)
for {
n, err := tr.Read(buftemp)
if err != nil {
if err == io.EOF {
break
}
return ret, err
}
if n > 0 {
_, err = gzw.Write(buftemp[:n])
if err != nil {
return ret, err
}
}
}
gzw.Close()
break
}
if !found {
return ret, fmt.Errorf("object %v not found in manifest", obj)
}
ret = bufw.Bytes()
return ret, nil
}
// ContentFromFile loads manifest content from a file on the file system (a gzip'd tar file),
// primarily utilized by mig-console during manifest creation operations
func (m *ManifestRecord) ContentFromFile(path string) (err error) {
var buf bytes.Buffer
fd, err := os.Open(path)
if err != nil {
return
}
defer fd.Close()
b64w := base64.NewEncoder(base64.StdEncoding, &buf)
b, err := ioutil.ReadAll(fd)
if err != nil {
return
}
_, err = b64w.Write(b)
if err != nil {
return
}
b64w.Close()
m.Content = buf.String()
return
}
// FileFromContent writes manifest content to a file on the file system
func (m *ManifestRecord) FileFromContent(path string) (err error) {
fd, err := os.Create(path)
if err != nil {
return
}
defer fd.Close()
bufr := bytes.NewBufferString(m.Content)
b64r := base64.NewDecoder(base64.StdEncoding, bufr)
b, err := ioutil.ReadAll(b64r)
if err != nil {
return
}
_, err = fd.Write(b)
if err != nil {
return
}
return nil
}
// ManifestParameters are sent from the loader to the API as part of
// a manifest request.
type ManifestParameters struct {
AgentIdentifier Agent `json:"agent"` // Agent context information
Object string `json:"object"` // Object being requested
}
// Validate validetes a ManifestParameters type for correct formatting
func (m *ManifestParameters) Validate() error {
return nil
}
// ValidateFetch validates the parameters included in a manifest request with an
// object fetch component
func (m *ManifestParameters) ValidateFetch() error {
err := m.Validate()
if err != nil {
return err
}
if m.Object == "" {
return fmt.Errorf("manifest fetch with no object")
}
return m.Validate()
}
// ManifestFetchResponse is the response to a manifest object fetch
type ManifestFetchResponse struct {
Data []byte `json:"data"`
}
// ManifestResponse is the response to a standard manifest request
type ManifestResponse struct {
LoaderName string `json:"loader_name"`
Entries []ManifestEntry `json:"entries"`
Signatures []string `json:"signatures"`
}
// Validate validates a ManifestResponse type ensuring required content is present
func (m *ManifestResponse) Validate() error {
if m.LoaderName == "" {
return fmt.Errorf("manifest response has no loader name")
}
return nil
}
// VerifySignatures verifies the signatures present in a manifest response against the keys
// present in keyring. It returns the number of valid unique signatures identified in the
// ManifestResponse.
func (m *ManifestResponse) VerifySignatures(keyring io.Reader) (validcnt int, err error) {
var sigs []string
// Copy signatures out of the response, and clear them as we do not
// include them as part of the JSON document in validation
sigs = make([]string, len(m.Signatures))
copy(sigs, m.Signatures)
m.Signatures = m.Signatures[:0]
mcopy := *m
// Also zero the loader name as it is not included in the signature
mcopy.LoaderName = ""
buf, err := json.Marshal(mcopy)
if err != nil {
return validcnt, err
}
// Create a copy of the keyring we can use during validation of each
// signature. We don't want to use the keyring directly as it is
// backed by a buffer and will be drained after verification of the
// first signature.
keycopy, err := ioutil.ReadAll(keyring)
if err != nil {
return validcnt, err
}
fpcache := make([]string, 0)
for _, x := range sigs {
keyreader := bytes.NewBuffer(keycopy)
valid, ent, err := pgp.Verify(string(buf), x, keyreader)
if err != nil {
return validcnt, err
}
if valid {
validcnt++
}
fp := hex.EncodeToString(ent.PrimaryKey.Fingerprint[:])
// Return an error if we have already cached this fingerprint
for _, x := range fpcache {
if x == fp {
err = fmt.Errorf("duplicate signature for fingerprint %v", fp)
return 0, err
}
}
fpcache = append(fpcache, fp)
}
return
}
// ManifestEntry describes an individual file element within a manifest
type ManifestEntry struct {
Name string `json:"name"` // Corresponds to a bundle name
SHA256 string `json:"sha256"` // SHA256 of entry
}
// BundleDictionaryEntry is used to map tokens within the loader manifest to
// objects on the file system. We don't allow specification of an exact path
// for interrogation or manipulation in the manifest. This results in some
// restrictions but hardens the loader against making unauthorized changes
// to the file system.
type BundleDictionaryEntry struct {
Name string
Path string
SHA256 string
Perm os.FileMode
}
// The various bundle entry maps below map filenames in the manifest to the location
// these files should be installed on the target platform.
//
// Note: take care when modifying these values; changing an existing manifest entry
// could cause problems if fetched by an older version of the loader. The map keys
// should be static and generally not be modified to retain compatibility.
var bundleEntryLinux = []BundleDictionaryEntry{
{"mig-agent", "/sbin/mig-agent", "", 0700},
{"mig-loader", "/sbin/mig-loader", "", 0700},
{"configuration", "/etc/mig/mig-agent.cfg", "", 0600},
{"agentcert", "/etc/mig/agent.crt", "", 0644},
{"agentkey", "/etc/mig/agent.key", "", 0600},
{"cacert", "/etc/mig/ca.crt", "", 0644},
{"loaderconfig", "/etc/mig/mig-loader.cfg", "", 0600},
}
var bundleEntryDarwin = []BundleDictionaryEntry{
{"mig-agent", "/usr/local/bin/mig-agent", "", 0700},
{"mig-loader", "/usr/local/bin/mig-loader", "", 0700},
{"configuration", "/etc/mig/mig-agent.cfg", "", 0600},
{"agentcert", "/etc/mig/agent.crt", "", 0644},
{"agentkey", "/etc/mig/agent.key", "", 0600},
{"cacert", "/etc/mig/ca.crt", "", 0644},
{"loaderconfig", "/etc/mig/mig-loader.cfg", "", 0600},
}
var bundleEntryWindows = []BundleDictionaryEntry{
{"mig-agent", "C:\\mig\\mig-agent.exe", "", 0700},
{"mig-loader", "C:\\mig\\mig-loader.exe", "", 0700},
{"configuration", "C:\\mig\\mig-agent.cfg", "", 0600},
{"agentcert", "C:\\mig\\agent.crt", "", 0644},
{"agentkey", "C:\\mig\\agent.key", "", 0600},
{"cacert", "C:\\mig\\ca.crt", "", 0644},
{"loaderconfig", "C:\\mig\\mig-loader.cfg", "", 0600},
}
// BundleDictionary maps GOOS platform names to specific bundle entry values
var BundleDictionary = map[string][]BundleDictionaryEntry{
"linux": bundleEntryLinux,
"darwin": bundleEntryDarwin,
"windows": bundleEntryWindows,
}
// GetHostBundle returns the correct BundleDictionaryEntry given the platform the
// code is executing on
func GetHostBundle() ([]BundleDictionaryEntry, error) {
switch runtime.GOOS {
case "linux":
return bundleEntryLinux, nil
case "darwin":
return bundleEntryDarwin, nil
case "windows":
return bundleEntryWindows, nil
}
return nil, fmt.Errorf("no entry for %v in bundle dictionary", runtime.GOOS)
}
// HashBundle populates a slice of BundleDictionaryEntrys, adding the SHA256 checksums
// from the file system
func HashBundle(b []BundleDictionaryEntry) ([]BundleDictionaryEntry, error) {
ret := b
for i := range ret {
fd, err := os.Open(ret[i].Path)
if err != nil {
// If the file does not exist we don't treat this as as
// an error. This is likely in cases with embedded
// configurations. In this case we leave the SHA256 as
// an empty string.
if os.IsNotExist(err) {
continue
}
return nil, err
}
h := sha256.New()
buf := make([]byte, 4096)
for {
n, err := fd.Read(buf)
if err != nil {
if err == io.EOF {
break
}
fd.Close()
return nil, err
}
if n > 0 {
h.Write(buf[:n])
}
}
fd.Close()
ret[i].SHA256 = fmt.Sprintf("%x", h.Sum(nil))
}
return ret, nil
}