~cmars/hockeypuck/master

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
/*
   Hockeypuck - OpenPGP key server
   Copyright (C) 2012-2014  Casey Marshall

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, version 3.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package openpgp

import (
	"crypto/md5"
	"crypto/sha256"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"hash"
	"io"
	"io/ioutil"
	"log"
	"sort"
	"time"

	"code.google.com/p/go.crypto/openpgp"
	"code.google.com/p/go.crypto/openpgp/armor"
	"code.google.com/p/go.crypto/openpgp/packet"
)

// Comparable time flag for "never expires"
var NeverExpires time.Time

var ErrMissingSignature = errors.New("Key material missing an expected signature")

func init() {
	t, err := time.Parse("2006-01-02 15:04:05 -0700", "9999-12-31 23:59:59 +0000")
	if err != nil {
		panic(err)
	}
	NeverExpires = t
}

// Get the public key fingerprint as a hex string.
func Fingerprint(pubkey *packet.PublicKey) string {
	return hex.EncodeToString(pubkey.Fingerprint[:])
}

// Get the public key fingerprint as a hex string.
func FingerprintV3(pubkey *packet.PublicKeyV3) string {
	return hex.EncodeToString(pubkey.Fingerprint[:])
}

func WritePackets(w io.Writer, root PacketRecord) error {
	err := root.Visit(func(rec PacketRecord) error {
		op, err := rec.GetOpaquePacket()
		if err != nil {
			return err
		}
		return op.Serialize(w)
	})
	if err != nil {
		return err
	}
	// Dump unsupported packets at the end.
	pubkey := root.(*Pubkey)
	for _, op := range pubkey.UnsupportedPackets() {
		err = op.Serialize(w)
		if err != nil {
			return err
		}
	}
	return nil
}

func WriteArmoredPackets(w io.Writer, root PacketRecord) error {
	armw, err := armor.Encode(w, openpgp.PublicKeyType, nil)
	defer armw.Close()
	if err != nil {
		return err
	}
	return WritePackets(armw, root)
}

type OpaqueKeyring struct {
	Packets      []*packet.OpaquePacket
	RFingerprint string
	Md5          string
	Sha256       string
	Error        error
}

type OpaqueKeyringChan chan *OpaqueKeyring

func ReadOpaqueKeyrings(r io.Reader) OpaqueKeyringChan {
	c := make(OpaqueKeyringChan)
	or := packet.NewOpaqueReader(r)
	go func() {
		defer close(c)
		var op *packet.OpaquePacket
		var err error
		var current *OpaqueKeyring
		for op, err = or.Next(); err == nil; op, err = or.Next() {
			switch op.Tag {
			case 6: //packet.PacketTypePublicKey:
				if current != nil {
					c <- current
					current = nil
				}
				current = new(OpaqueKeyring)
				fallthrough
			case 13: //packet.PacketTypeUserId:
				fallthrough
			case 17: //packet.PacketTypeUserAttribute:
				fallthrough
			case 14: //packet.PacketTypePublicSubkey:
				fallthrough
			case 2: //packet.PacketTypeSignature:
				current.Packets = append(current.Packets, op)
			}
		}
		if err == io.EOF && current != nil {
			c <- current
		} else if err != nil {
			c <- &OpaqueKeyring{Error: err}
		}
	}()
	return c
}

// SksDigest calculates a cumulative message digest on all
// OpenPGP packets for a given primary public key,
// using the same ordering as SKS, the Synchronizing Key Server.
// Use MD5 for matching digest values with SKS.
func SksDigest(key *Pubkey, h hash.Hash) string {
	var packets packetSlice
	key.Visit(func(rec PacketRecord) error {
		if opkt, err := rec.GetOpaquePacket(); err != nil {
			panic(fmt.Sprintf(
				"Error parsing packet: %v public key fingerprint: %v", err, key.Fingerprint()))
		} else {
			packets = append(packets, opkt)
		}
		return nil
	})
	packets = append(packets, key.UnsupportedPackets()...)
	return sksDigestOpaque(packets, h)
}

func sksDigestOpaque(packets []*packet.OpaquePacket, h hash.Hash) string {
	sort.Sort(sksPacketSorter{packets})
	for _, opkt := range packets {
		binary.Write(h, binary.BigEndian, int32(opkt.Tag))
		binary.Write(h, binary.BigEndian, int32(len(opkt.Contents)))
		h.Write(opkt.Contents)
	}
	return hex.EncodeToString(h.Sum(nil))
}

type ReadKeyResult struct {
	*Pubkey
	Error error
}

type ReadKeyResults []*ReadKeyResult

func (r ReadKeyResults) GoodKeys() (result []*Pubkey) {
	for _, rkr := range r {
		if rkr.Error == nil {
			result = append(result, rkr.Pubkey)
		}
	}
	return
}

type PubkeyChan chan *ReadKeyResult

func ErrReadKeys(msg string) *ReadKeyResult {
	return &ReadKeyResult{Error: errors.New(msg)}
}

func (pubkey *Pubkey) updateDigests() {
	pubkey.Md5 = SksDigest(pubkey, md5.New())
	pubkey.Sha256 = SksDigest(pubkey, sha256.New())
}

func ReadKeys(r io.Reader) PubkeyChan {
	c := make(PubkeyChan)
	go func() {
		defer close(c)
		for keyRead := range readKeys(r) {
			if keyRead.Error == nil {
				Resolve(keyRead.Pubkey)
			}
			c <- keyRead
		}
	}()
	return c
}

func dumpBadKey(opkr *OpaqueKeyring) {
	f, err := ioutil.TempFile("", "hockeypuck-badkey")
	if err != nil {
		log.Println("Failed to dump bad key to temp file:", err)
		return
	}
	defer f.Close()
	for _, pkt := range opkr.Packets {
		err = pkt.Serialize(f)
		if err != nil {
			log.Println("Error writing bad key to temp file:", err)
			return
		}
	}
	log.Println("Bad key written to", f.Name())
}

// Read one or more public keys from input.
func readKeys(r io.Reader) PubkeyChan {
	c := make(PubkeyChan)
	go func() {
		defer close(c)
		var err error
		var pubkey *Pubkey
		var signable Signable
		for opkr := range ReadOpaqueKeyrings(r) {
			pubkey = nil
			for _, opkt := range opkr.Packets {
				var badPacket *packet.OpaquePacket
				switch opkt.Tag {
				case 6: //packet.PacketTypePublicKey:
					if pubkey != nil {
						log.Println("On pubkey:", pubkey)
						log.Println("Found embedded primary pubkey:", opkt)
						panic("Multiple primary public keys in keyring")
					}
					if pubkey, err = NewPubkey(opkt); err != nil {
						log.Println("On (opaque) pubkey:", opkt)
						log.Println(err)
						dumpBadKey(opkr)
						panic("Failed to parse primary pubkey")
					}
					signable = pubkey
				case 14: //packet.PacketTypePublicSubkey:
					var subkey *Subkey
					if subkey, err = NewSubkey(opkt); err != nil {
						badPacket = opkt
						signable = nil
					} else {
						pubkey.subkeys = append(pubkey.subkeys, subkey)
						signable = subkey
					}
				case 13: //packet.PacketTypeUserId:
					var userId *UserId
					if userId, err = NewUserId(opkt); err != nil {
						badPacket = opkt
						signable = nil
					} else {
						pubkey.userIds = append(pubkey.userIds, userId)
						signable = userId
					}
				case 17: //packet.PacketTypeUserAttribute:
					var userAttr *UserAttribute
					if userAttr, err = NewUserAttribute(opkt); err != nil {
						badPacket = opkt
						signable = nil
					} else {
						pubkey.userAttributes = append(pubkey.userAttributes, userAttr)
						signable = userAttr
					}
				case 2: //packet.PacketTypeSignature:
					var sig *Signature
					if sig, err = NewSignature(opkt); err != nil {
						badPacket = opkt
						signable = nil
					} else if signable == nil {
						badPacket = opkt
					} else {
						signable.AddSignature(sig)
					}
				default:
					badPacket = opkt
				}
				if badPacket != nil {
					pubkey.AppendUnsupported(badPacket)
				}
			}
			if pubkey == nil {
				c <- &ReadKeyResult{Error: errors.New("No primary public key found")}
				continue
			}
			// Update the overall public key material digest.
			pubkey.updateDigests()
			// Validate signatures and wire-up relationships.
			// Also flags invalid key material but does not remove it.
			Resolve(pubkey)
			c <- &ReadKeyResult{Pubkey: pubkey}
		}
	}()
	return c
}