Debian Codegraph @

ox.go

raw
1 // Copyright Martin Dosch.
2 // Use of this source code is governed by the BSD-2-clause
3 // license that can be found in the LICENSE file.
4
5 // TODO: Add more logging
6 // TODO: Deduplicate code
7
8 package main
9
10 import (
11 "encoding/base64"
12 "fmt"
13 "io"
14 "log/slog"
15 "os"
16 "runtime"
17 "strings"
18 "time"
19
20 "github.com/ProtonMail/gopenpgp/v3/crypto" // MIT License
21 "github.com/beevik/etree" // BSD-2-clause
22 "github.com/xmppo/go-xmpp" // BSD-3-Clause
23 )
24
25 func oxDeleteNodes(jid string, client *xmpp.Client, iqc chan xmpp.IQ, disc chan xmpp.DiscoItems) error {
26 discoItems, err := getDiscoItems(client, disc, jid)
27 if err != nil {
28 return fmt.Errorf("ox: delete nodes: failed to create node list request %w", err)
29 }
30 slog.Info("ox: parsing reply to IQ")
31 for _, item := range discoItems.Items {
32 if !strings.Contains(item.Node, nsOx) {
33 continue
34 }
35 deleteNodeRequest := etree.NewDocument()
36 deleteNodeRequest.WriteSettings.AttrSingleQuote = true
37 pubsub := deleteNodeRequest.CreateElement("pubsub")
38 pubsub.CreateAttr("xmlns", nsPubsubOwner)
39 del := pubsub.CreateElement("delete")
40 del.CreateAttr("node", item.Node)
41 dnr, err := deleteNodeRequest.WriteToString()
42 if err != nil {
43 continue
44 }
45 slog.Info("ox: sending IQ to list pep nodes", "node", item.Node)
46 _, err = sendIQ(client, iqc, jid, "set", dnr)
47 if err != nil {
48 continue
49 }
50 }
51 return nil
52 }
53
54 func oxDecrypt(m xmpp.Chat, client *xmpp.Client, iqc chan xmpp.IQ, drc chan xmpp.DiscoResult,
55 user string, oxPrivKey *crypto.Key, oxTrustMode string,
56 ) (string, time.Time, error) {
57 var cryptMsgByte []byte
58 var senderKeyRing *crypto.KeyRing
59 var err error
60 sender := strings.Split(m.Remote, "/")[0]
61 for _, r := range m.OtherElem {
62 if r.XMLName.Space == nsOx {
63 cryptMsgByte, err = base64.StdEncoding.DecodeString(r.InnerXML)
64 if err != nil {
65 return strError, time.Now(), err
66 }
67 break
68 }
69 }
70 oxMsg := crypto.NewPGPMessage(cryptMsgByte)
71 keyRing, err := crypto.NewKeyRing(oxPrivKey)
72 if err != nil {
73 return strError, time.Now(), err
74 }
75 slog.Info("ox: decrypting: getting senders key", "sender", sender)
76 if m.Type == "groupchat" {
77 senderKeyRing, err = oxGetPublicKeyRingChatroom(client, iqc, drc, sender, oxTrustMode)
78 if err != nil {
79 return strError, time.Now(), err
80 }
81 } else {
82 senderKeyRing, err = oxGetPublicKeyRing(client, iqc, sender, oxTrustMode)
83 if err != nil {
84 return strError, time.Now(), err
85 }
86 }
87 slog.Info("ox: decrypting message")
88 pgpDecrypt, err := crypto.PGP().Decryption().
89 DecryptionKeys(keyRing).
90 VerificationKeys(senderKeyRing).
91 New()
92 if err != nil {
93 return strError, time.Now(), err
94 }
95 decryptMsg, err := pgpDecrypt.Decrypt(oxMsg.Bytes(), crypto.Bytes)
96 if err != nil {
97 return strError, time.Now(), err
98 }
99 // Remove invalid code points.
100 slog.Info("ox: removing invalid code points from decrypted message")
101 message := validUTF8(decryptMsg.String())
102 doc := etree.NewDocument()
103 err = doc.ReadFromString(message)
104 if err != nil {
105 return strError, time.Now(), err
106 }
107 slog.Info("ox: decrypting: checking signcrypt element")
108 signcrypt := doc.SelectElement("signcrypt")
109 if signcrypt == nil {
110 return strError, time.Now(), fmt.Errorf("ox: no signcrypt element")
111 }
112 slog.Info("ox: decrypting: checking to element")
113 to := signcrypt.SelectElement("to")
114 if to == nil {
115 return strError, time.Now(), fmt.Errorf("ox: no to element")
116 }
117 slog.Info("ox: decrypting: checking jid attribute")
118 jid := to.SelectAttr("jid")
119 if jid == nil {
120 return strError, time.Now(), fmt.Errorf("ox: no jid attribute")
121 }
122 jidAttrib := strings.Split(jid.Value, "/")[0]
123 slog.Info("ox: decrypting: comparing jid attribute with local user",
124 "jid-attribute", jidAttrib, "user", user)
125 if jidAttrib != user && m.Type != "groupchat" {
126 return strError, time.Now(), fmt.Errorf("ox: encrypted for wrong user")
127 }
128 slog.Info("ox: decrypting: checking time element")
129 timestamp := signcrypt.SelectElement("time")
130 if timestamp == nil {
131 return strError, time.Now(), fmt.Errorf("ox: no time element")
132 }
133 slog.Info("ox: decrypting: checking stamp attribute")
134 stamp := timestamp.SelectAttr("stamp")
135 if stamp == nil {
136 return strError, time.Now(), fmt.Errorf("ox: no stamp attribute")
137 }
138 slog.Info("ox: decrypting: parsing time stamp")
139 msgStamp, err := time.Parse("2006-01-02T15:04:05Z0700", stamp.Value)
140 if err != nil {
141 return strError, time.Now(), err
142 }
143 slog.Info("ox: decrypting: checking payload element")
144 payload := signcrypt.SelectElement("payload")
145 if payload == nil {
146 return strError, time.Now(), fmt.Errorf("ox: no payload element")
147 }
148 slog.Info("ox: decrypting: checking body element")
149 body := payload.SelectElement("body")
150 if body == nil {
151 return "", time.Now(), nil
152 }
153 slog.Info("ox: decrypting: returning body")
154 return body.Text(), msgStamp, nil
155 }
156
157 func isOxMsg(m xmpp.Chat) bool {
158 slog.Info("ox: checking for ox message")
159 for _, r := range m.OtherElem {
160 slog.Info("ox: checking for ox message: comparing", "XMLNameSpace", r.XMLName.Space,
161 "OXNameSpace", nsOx)
162 if r.XMLName.Space == nsOx {
163 slog.Info("ox: checking for ox message:", "result", true)
164 return true
165 }
166 }
167 slog.Info("ox: checking for ox message:", "result", false)
168 return false
169 }
170
171 func oxImportPrivKey(jid string, privKeyLocation string, client *xmpp.Client, iqc chan xmpp.IQ,
172 oxTrustMode string,
173 ) error {
174 xmppURI := "xmpp:" + jid
175 slog.Info("ox: importing private key:", "xmpp-uri", xmppURI)
176 slog.Info("ox: importing private key:", "location", privKeyLocation)
177 buffer, err := readFile(privKeyLocation)
178 if err != nil {
179 return err
180 }
181 slog.Info("ox: importing private key: reading key")
182 key, err := crypto.NewKey(buffer.Bytes())
183 if err != nil {
184 slog.Info("ox: importing private key: reading key failed: checking if armored")
185 key, err = crypto.NewKeyFromArmored(buffer.String())
186 if err != nil {
187 keyDecoded, err := base64.StdEncoding.DecodeString(buffer.String())
188 slog.Info("ox: importing private key: reading key failed: checking if base64 encoded")
189 if err != nil {
190 return fmt.Errorf("ox: import privkey: failed to import private key: %w", err)
191 }
192 slog.Info("ox: importing private key: reading key")
193 key, err = crypto.NewKey(keyDecoded)
194 if err != nil {
195 return fmt.Errorf("ox: import privkey: failed to import private key: %w", err)
196 }
197 }
198 }
199 slog.Info("ox: importing private key: reading key: success")
200 entity := key.GetEntity()
201 slog.Info("ox: importing private key:", "entity", entity)
202 if entity.Identities[xmppURI] == nil {
203 return fmt.Errorf("ox: key identity is not %s", xmppURI)
204 }
205 slog.Info("ox: importing private key: deriving public key")
206 pk, err := key.GetPublicKey()
207 if err != nil {
208 return fmt.Errorf("ox: import privkey: failed to get public key associated to private key: %w", err)
209 }
210 pubKey, err := crypto.NewKey(pk)
211 if err != nil {
212 return fmt.Errorf("ox: import privkey: failed to get public key associated to private key: %w", err)
213 }
214 fingerprint := strings.ToUpper(pubKey.GetFingerprint())
215 slog.Info("ox: importing private key:", "fingerprint", fingerprint)
216 slog.Info("ox: importing private key: checking if public key is already published")
217 _, err = oxRecvPublicKeys(client, iqc, jid, fingerprint)
218 if err != nil {
219 slog.Info("ox: importing private key: publishing public key")
220 err = oxPublishPubKey(jid, client, iqc, pubKey)
221 if err != nil {
222 return fmt.Errorf("ox: import privkey: failed to publish public key: %w", err)
223 }
224 }
225 location, err := oxGetPrivKeyLoc(jid)
226 if err != nil {
227 return fmt.Errorf("ox: import privkey: failed to determine private key location: %w", err)
228 }
229 slog.Info("ox: importing private key: getting private key location", "jid", jid, "location", location)
230 slog.Info("ox: importing private key: serializing key")
231 keySerialized, err := key.Serialize()
232 if err != nil {
233 return fmt.Errorf("ox: import privkey: failed to serialize private key: %w", err)
234 }
235 slog.Info("ox: importing private key: storing key:", "location", location)
236 err = oxStoreKey(location,
237 base64.StdEncoding.EncodeToString(keySerialized))
238 if err != nil {
239 return fmt.Errorf("ox: import privkey: failed to store private key: %w", err)
240 }
241 slog.Info("ox: importing private key: requesting public key ring")
242 pubKeyRing, err := oxGetPublicKeyRing(client, iqc, jid, oxTrustMode)
243 if err == nil {
244 slog.Info("ox: importing private key: checking if public key ring contains", "fingerprint", fingerprint)
245 pubKeys := pubKeyRing.GetKeys()
246 for _, r := range pubKeys {
247 fp := strings.ToUpper(r.GetFingerprint())
248 slog.Info("ox: importing private key: checking", "fingerprint", fp)
249 if fp == fingerprint {
250 slog.Info("ox: importing private key: checking if public key ring contains fingerprint: success")
251 return nil
252 }
253 }
254 }
255 slog.Info("ox: importing private key: publishing public key")
256 err = oxPublishPubKey(jid, client, iqc, pubKey)
257 if err != nil {
258 return fmt.Errorf("ox: import privkey: failed to publish public key: %w", err)
259 }
260 return nil
261 }
262
263 func oxPublishPubKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ, pubKey *crypto.Key) error {
264 keyCreated := time.Now().UTC().Format("2006-01-02T15:04:05Z")
265 fingerprint := strings.ToUpper(pubKey.GetFingerprint())
266 slog.Info("ox: publishing public key:", "fingerprint", fingerprint, "created", keyCreated)
267 slog.Info("ox: publishing public key: serializing public key")
268 keySerialized, err := pubKey.Serialize()
269 if err != nil {
270 return fmt.Errorf("ox: publish pubkey: failed to serialize pubkey: %w", err)
271 }
272 slog.Info("ox: publishing public key: base64 encoding public key")
273 pubKeyBase64 := base64.StdEncoding.EncodeToString(keySerialized)
274 root := etree.NewDocument()
275 root.WriteSettings.AttrSingleQuote = true
276 pubsub := root.CreateElement("pubsub")
277 pubsub.CreateAttr("xmlns", nsPubsub)
278 publish := pubsub.CreateElement("publish")
279 publish.CreateAttr("node", nsOxPubKeys+":"+fingerprint)
280 item := publish.CreateElement("item")
281 item.CreateAttr("id", keyCreated)
282 pubkey := item.CreateElement("pubkey")
283 pubkey.CreateAttr("xmlns", nsOx)
284 data := pubkey.CreateElement("data")
285 data.CreateText(pubKeyBase64)
286 publishoptions := pubsub.CreateElement("publish-options")
287 x := publishoptions.CreateElement("x")
288 x.CreateAttr("xmlns", nsJabberData)
289 x.CreateAttr("type", "submit")
290 field := x.CreateElement("field")
291 field.CreateAttr("var", "FORM_TYPE")
292 field.CreateAttr("type", "hidden")
293 value := field.CreateElement("value")
294 value.CreateText(pubsubPubOptions)
295 field = x.CreateElement("field")
296 field.CreateAttr("var", "pubsub#access_model")
297 value = field.CreateElement("value")
298 value.CreateText("open")
299 xmlstring, err := root.WriteToString()
300 if err != nil {
301 return fmt.Errorf("ox: publish pubkey: failed to create publish public key iq xml: %w", err)
302 }
303 slog.Info("ox: publishing public key: sending IQ")
304 iqReply, err := sendIQ(client, iqc, jid, "set", xmlstring)
305 if err != nil {
306 return fmt.Errorf("ox: publish pubkey: iq failure publishing public key: %w", err)
307 }
308 if iqReply.Type != strResult {
309 return fmt.Errorf("ox: error while publishing public key")
310 }
311 slog.Info("ox: publishing public key: received result")
312 slog.Info("ox: publishing public key: receiving own public key from pubsub")
313 ownPubKeyRingFromPubsub, err := oxRecvPublicKeys(client, iqc, jid, fingerprint)
314 if err != nil {
315 return fmt.Errorf("ox: couldn't successfully verify public key upload")
316 }
317 ownPubKeyFromPubsub := ownPubKeyRingFromPubsub.GetKeys()[0]
318 slog.Info("ox: publishing public key: serializing own public key received from pubsub")
319 ownPubKeyFromPubsubSerialized, err := ownPubKeyFromPubsub.Serialize()
320 if err != nil {
321 return fmt.Errorf("ox: couldn't successfully verify public key upload")
322 }
323 slog.Info("ox: publishing public key: base64 encoding own public key received from pubsub")
324 psPubKeyBase64 := base64.StdEncoding.EncodeToString(ownPubKeyFromPubsubSerialized)
325 slog.Info("ox: publishing public key: comparing local and pubsub public key:", "local", pubKeyBase64, "pubsub", psPubKeyBase64)
326 if pubKeyBase64 != psPubKeyBase64 {
327 return fmt.Errorf("ox: couldn't successfully verify public key upload")
328 }
329 slog.Info("ox: publishing public key: comparing local and pubsub public key: success")
330 root = etree.NewDocument()
331 root.WriteSettings.AttrSingleQuote = true
332 pubsub = root.CreateElement("pubsub")
333 pubsub.CreateAttr("xmlns", nsPubsub)
334 publish = pubsub.CreateElement("publish")
335 publish.CreateAttr("node", nsOxPubKeys)
336 item = publish.CreateElement("item")
337 pubkeyslist := item.CreateElement("public-keys-list")
338 pubkeyslist.CreateAttr("xmlns", nsOx)
339 pubkeymeta := pubkeyslist.CreateElement("pubkey-metadata")
340 pubkeymeta.CreateAttr("v4-fingerprint", fingerprint)
341 pubkeymeta.CreateAttr("date", keyCreated)
342 publishoptions = pubsub.CreateElement("publish-options")
343 x = publishoptions.CreateElement("x")
344 x.CreateAttr("xmlns", nsJabberData)
345 x.CreateAttr("type", "submit")
346 field = x.CreateElement("field")
347 field.CreateAttr("var", "FORM_TYPE")
348 field.CreateAttr("type", "hidden")
349 value = field.CreateElement("value")
350 value.CreateText(pubsubPubOptions)
351 field = x.CreateElement("field")
352 field.CreateAttr("var", "pubsub#access_model")
353 value = field.CreateElement("value")
354 value.CreateText("open")
355 xmlstring, err = root.WriteToString()
356 if err != nil {
357 return fmt.Errorf("ox: publish pubkey: failed to create xml for iq to publish public key list: %w", err)
358 }
359 slog.Info("ox: publishing public key: sending IQ to publish key list to pubsub")
360 iqReply, err = sendIQ(client, iqc, jid, "set", xmlstring)
361 if err != nil {
362 return fmt.Errorf("ox: publish pubkey: iq failure publishing public key list: %w", err)
363 }
364 if iqReply.Type != strResult {
365 return fmt.Errorf("ox: couldn't publish public key list")
366 }
367 slog.Info("ox: publishing public key: received result")
368 return nil
369 }
370
371 func oxGetPrivKeyLoc(jid string) (string, error) {
372 dataDir, err := getDataPath(fsFriendlyJid(jid), true)
373 slog.Info("ox: get private key location: trying", "location", dataDir)
374 if err != nil {
375 return strError, fmt.Errorf("ox: get privkey location: %w", err)
376 }
377 oldDataDir, err := getDataPath("oxprivkeys/", false)
378 slog.Info("ox: get private key location: trying", "location", oldDataDir)
379 if err != nil {
380 return strError, fmt.Errorf("ox: get privkey location: %w", err)
381 }
382 // TODO: Remove handling of oldDataFile in a later version when it's very likely that there are no
383 // more versions in use using the oldDataFile (<0.8.3).
384 oldDataFile := oldDataDir + base64.StdEncoding.EncodeToString([]byte(jid))
385 oldDataFile2 := oldDataDir + strings.ReplaceAll(jid, "@", "_at_")
386 oldDataFile3 := oldDataDir + fsFriendlyJid(jid)
387 dataFile := dataDir + "oxprivkey"
388 if _, err := os.Stat(oldDataFile); err == nil {
389 err := os.Rename(oldDataFile, dataFile)
390 slog.Info("ox: get private key location: moving file to new location", "old", oldDataFile, "new", dataFile)
391 if err != nil {
392 return dataFile, err
393 }
394 }
395 if _, err := os.Stat(oldDataFile2); err == nil {
396 slog.Info("ox: get private key location: moving file to new location", "old", oldDataFile2, "new", dataFile)
397 err := os.Rename(oldDataFile2, dataFile)
398 if err != nil {
399 return dataFile, err
400 }
401 }
402 if _, err := os.Stat(oldDataFile3); err == nil {
403 slog.Info("ox: get private key location: moving file to new location", "old", oldDataFile3, "new", dataFile)
404 err := os.Rename(oldDataFile3, dataFile)
405 if err != nil {
406 return dataFile, err
407 }
408 }
409 // #nosec G304 -- old data dir comes from the local system, it's no untrusted input from the network
410 dir, err := os.Open(oldDataDir)
411 if err == nil {
412 slog.Info("ox: get private key location: entering old data", "folder", oldDataDir)
413 slog.Info("ox: get private key location: checking if directory is empty")
414 _, err = dir.ReadDir(1)
415 // Delete old data dir if empty.
416 if err == io.EOF {
417 slog.Info("ox: get private key location: trying to delete empty", "folder", oldDataDir)
418 err = os.Remove(oldDataDir)
419 if err != nil {
420 fmt.Printf("oxGetPrivKeyLoc: failed to delete old private key location: %v\n", err)
421 }
422 }
423 }
424 return dataFile, nil
425 }
426
427 func oxGetPubKeyLoc(jid string) (string, error) {
428 dataDir, err := getDataPath("oxpubkeys/", true)
429 slog.Info("ox: getting public key", "location", dataDir)
430 if err != nil {
431 return strError, fmt.Errorf("ox: get pubkey location: %w", err)
432 }
433 dataFile := dataDir + fsFriendlyJid(jid)
434 slog.Info("ox: getting public key location", "file", dataFile)
435 return dataFile, nil
436 }
437
438 func oxGetPrivKey(jid string, passphrase string) (*crypto.Key, error) {
439 dataFile, err := oxGetPrivKeyLoc(jid)
440 if err != nil {
441 return nil, fmt.Errorf("ox: get privkey: failed to get private key location: %w", err)
442 }
443 slog.Info("ox: getting private key:", "file", dataFile)
444 keyBuffer, err := readFile(dataFile)
445 if err != nil {
446 return nil, fmt.Errorf("ox: get privkey: failed to read private key: %w", err)
447 }
448 keyString := keyBuffer.String()
449 slog.Info("ox: getting private key: base64 decoding key")
450 decodedPrivKey, err := base64.StdEncoding.DecodeString(keyString)
451 if err != nil {
452 return nil, fmt.Errorf("ox: get privkey: failed to decode private key: %w", err)
453 }
454 slog.Info("ox: getting private key: decoding key")
455 key, err := crypto.NewKey(decodedPrivKey)
456 if err != nil {
457 return nil, fmt.Errorf("ox: get privkey: failed to decode private key: %w", err)
458 }
459 if passphrase != "" {
460 slog.Info("ox: getting private key: unlocking key", "passphrase", "REDACTED")
461 key, err = key.Unlock([]byte(passphrase))
462 if err != nil {
463 return nil, fmt.Errorf("ox: failed to unlock private key: %w", err)
464 }
465 }
466 isLocked, err := key.IsLocked()
467 if err != nil {
468 return nil, fmt.Errorf("ox: get privkey: failed to check whether private key is locked: %w", err)
469 }
470 if isLocked {
471 return nil, fmt.Errorf("ox: get privkey: failed to unlock private key: %w", err)
472 }
473 slog.Info("ox: getting private checking if key is expired")
474 if key.IsExpired(time.Now().Unix()) {
475 return nil, fmt.Errorf("ox: private key is expired: %s", key.GetFingerprint())
476 }
477 return key, nil
478 }
479
480 func oxStoreKey(location string, key string) error {
481 var file *os.File
482 slog.Info("ox: storing key:", "location", location)
483 // #nosec G304 -- location comes from the local system, it's no untrusted input from the network
484 file, err := os.Create(location)
485 if err != nil {
486 return fmt.Errorf("ox: store key: failed to create key location: %w", err)
487 }
488 if runtime.GOOS != "windows" {
489 _ = file.Chmod(os.FileMode(defaultFileRights))
490 } else {
491 _ = file.Chmod(os.FileMode(defaultFileRightsWin))
492 }
493 slog.Info("ox: storing key: writing key to file")
494 _, err = file.Write([]byte(key))
495 if err != nil {
496 return fmt.Errorf("ox: store key: failed to write key to file: %w", err)
497 }
498 err = file.Close()
499 if err != nil {
500 fmt.Println("error while closing file:", err)
501 }
502 return nil
503 }
504
505 func oxGenPrivKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ,
506 passphrase string, keyType int,
507 ) error {
508 xmppURI := "xmpp:" + jid
509 slog.Info("ox: generating privkey:", "jid", xmppURI, "keytype", keyType)
510 pgp := crypto.PGP()
511 privKey, err := pgp.KeyGeneration().
512 AddUserId(xmppURI, "").
513 OverrideProfileAlgorithm(keyType).
514 New().GenerateKey()
515 if err != nil {
516 return fmt.Errorf("ox: generate privkey: failed to generate private key: %w", err)
517 }
518 key := privKey
519 if passphrase != "" {
520 slog.Info("ox: generating privkey: setting", "passphrase", "REDACTED")
521 key, err = pgp.LockKey(privKey, []byte(passphrase))
522 if err != nil {
523 return fmt.Errorf("ox: generate privkey: failed to lock private key with passphrase: %w", err)
524 }
525 }
526 slog.Info("ox: generating privkey: serializing key")
527 keySerialized, err := key.Serialize()
528 if err != nil {
529 return fmt.Errorf("ox: generate privkey: failed to serialize private key: %w", err)
530 }
531 location, err := oxGetPrivKeyLoc(jid)
532 if err != nil {
533 return fmt.Errorf("ox: generate privkey: failed to get private key location: %w", err)
534 }
535 slog.Info("ox: generating privkey: storing base64 encoded key:", "location", location)
536 err = oxStoreKey(location,
537 base64.StdEncoding.EncodeToString(keySerialized))
538 if err != nil {
539 return fmt.Errorf("ox: generate privkey: failed store private key: %w", err)
540 }
541 slog.Info("ox: generating privkey: deriving public key")
542 decodedPubKey, err := key.GetPublicKey()
543 if err != nil {
544 return fmt.Errorf("ox: generate privkey: failed to decode public key: %w", err)
545 }
546 pubKey, err := crypto.NewKey(decodedPubKey)
547 if err != nil {
548 return fmt.Errorf("ox: generate privkey: failed to decode public key: %w", err)
549 }
550 err = oxPublishPubKey(jid, client, iqc, pubKey)
551 if err != nil {
552 return fmt.Errorf("ox: generate privkey: failed to publish public key: %w", err)
553 }
554 return nil
555 }
556
557 func oxRecvPublicKeys(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, fingerprint string) (*crypto.KeyRing, error) {
558 opkr := etree.NewDocument()
559 opkr.WriteSettings.AttrSingleQuote = true
560 opkrPs := opkr.CreateElement("pubsub")
561 opkrPs.CreateAttr("xmlns", nsPubsub)
562 opkrPsItems := opkrPs.CreateElement("items")
563 opkrPsItems.CreateAttr("node", nsOxPubKeys+":"+fingerprint)
564 opkrPsItems.CreateAttr("max_items", "1")
565 opkrString, err := opkr.WriteToString()
566 if err != nil {
567 return nil, fmt.Errorf("ox: receive public keys: failed to generate xml for public key request: %w", err)
568 }
569 slog.Info("ox: receiving public keys:", "recipient", recipient)
570 oxPublicKey, err := sendIQ(client, iqc, recipient, "get", opkrString)
571 if err != nil {
572 return nil, fmt.Errorf("ox: receive public keys: iq error requesting public keys: %w", err)
573 }
574 if oxPublicKey.Type != strResult {
575 return nil, fmt.Errorf("ox: error while requesting public key for %s",
576 recipient)
577 }
578 oxPublicKeyXML := etree.NewDocument()
579 err = oxPublicKeyXML.ReadFromBytes(oxPublicKey.Query)
580 if err != nil {
581 return nil, fmt.Errorf("ox: receive public keys: failed parsing iq reply to public key request: %w", err)
582 }
583 keyring, err := crypto.NewKeyRing(nil)
584 if err != nil {
585 return nil, fmt.Errorf("ox: receive public keys: failed reading public key: %w", err)
586 }
587 oxPublicKeyXMLPubsub := oxPublicKeyXML.SelectElement("pubsub")
588 if oxPublicKeyXMLPubsub == nil {
589 return nil, fmt.Errorf("ox: no pubsub element in reply to public key request")
590 }
591 oxPublicKeyXMLItems := oxPublicKeyXMLPubsub.SelectElement("items")
592 if oxPublicKeyXMLItems == nil {
593 return nil, fmt.Errorf("ox: no items element in reply to public key request")
594 }
595 oxPublicKeyXMLItem := oxPublicKeyXMLItems.SelectElement("item")
596 if oxPublicKeyXMLItem == nil {
597 return nil, fmt.Errorf("ox: no item element in reply to public key request")
598 }
599 slog.Info("ox: receiving public keys: received public keys")
600 oxPublicKeyXMLPubkey := oxPublicKeyXMLItem.SelectElements("pubkey")
601 slog.Info("ox: receiving public keys: decoding public", "key", oxPublicKeyXMLPubkey[0])
602 data := oxPublicKeyXMLPubkey[0].SelectElement("data")
603 if data == nil {
604 return nil, fmt.Errorf("ox: receive public keys: no data element")
605 }
606 decodedPubKey, err := base64.StdEncoding.DecodeString(data.Text())
607 if err != nil {
608 return nil, fmt.Errorf("ox: receive public keys: failed to decode public key: %w", err)
609 }
610 key, err := crypto.NewKey(decodedPubKey)
611 if err != nil {
612 return nil, fmt.Errorf("ox: receive public keys: failed to decode public key: %w", err)
613 }
614 if strings.ToUpper(key.GetFingerprint()) != fingerprint {
615 return nil, fmt.Errorf("ox: receive public keys: received key has fingerprint %s but %s was advertised",
616 strings.ToUpper(key.GetFingerprint()), fingerprint)
617 }
618 slog.Info("ox: receiving public keys: checking for expiry:", "fingerprint", fingerprint)
619 if key.IsExpired(time.Now().Unix()) {
620 return nil, fmt.Errorf("ox: key is expired: %s", fingerprint)
621 }
622 err = keyring.AddKey(key)
623 if err != nil {
624 return nil, fmt.Errorf("ox: receive public keys: failed adding public key to keyring: %w", err)
625 }
626 return keyring, nil
627 }
628
629 func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, oxTrustMode string,
630 ) (*crypto.KeyRing, error) {
631 publicKeyRing, err := crypto.NewKeyRing(nil)
632 if err != nil {
633 return nil, fmt.Errorf("ox: get public keyring: failed to create a new keyring: %w", err)
634 }
635
636 oxPubKeyListReq := etree.NewDocument()
637 oxPubKeyListReq.WriteSettings.AttrSingleQuote = true
638 oxPubKeyListReqPs := oxPubKeyListReq.CreateElement("pubsub")
639 oxPubKeyListReqPs.CreateAttr("xmlns", nsPubsub)
640 oxPubKeyListReqPsItems := oxPubKeyListReqPs.CreateElement("items")
641 oxPubKeyListReqPsItems.CreateAttr("node", nsOxPubKeys)
642 oxPubKeyListReqPsItems.CreateAttr("max_items", "1")
643 opkl, err := oxPubKeyListReq.WriteToString()
644 if err != nil {
645 return nil, fmt.Errorf("ox: %w", err)
646 }
647 oxPublicKeyList, err := sendIQ(client, iqc, recipient, "get", opkl)
648 if err != nil {
649 return nil, fmt.Errorf("ox: %w", err)
650 }
651 if oxPublicKeyList.Type != strResult {
652 return nil, fmt.Errorf("ox: error while requesting public openpgp keys for %s",
653 recipient)
654 }
655 oxPubKeyListXML := etree.NewDocument()
656 err = oxPubKeyListXML.ReadFromBytes(oxPublicKeyList.Query)
657 if err != nil {
658 return nil, fmt.Errorf("ox: get public keyring: failed to parse answer to public key list request: %w", err)
659 }
660
661 pubKeyRingID := "none"
662 newestKey, err := time.Parse(time.RFC3339, "1900-01-01T00:00:00Z")
663 if err != nil {
664 return nil, fmt.Errorf("ox: get public keyring: failed to set time for newest key to 1900-01-01: %w", err)
665 }
666
667 oxPubKeyListXMLPubsub := oxPubKeyListXML.SelectElement("pubsub")
668 if oxPubKeyListXMLPubsub == nil {
669 return nil, fmt.Errorf("ox: no pubsub element in public key list")
670 }
671 oxPubKeyListXMLPubsubItems := oxPubKeyListXMLPubsub.SelectElement("items")
672 if oxPubKeyListXMLPubsubItems == nil {
673 return nil, fmt.Errorf("ox: no items element in public key list")
674 }
675 oxPubKeyListXMLPubsubItemsItem := oxPubKeyListXMLPubsubItems.SelectElement("item")
676 if oxPubKeyListXMLPubsubItemsItem == nil {
677 return nil, fmt.Errorf("ox: no item element in public key list")
678 }
679 oxPubKeyListXMLPubsubItemsItemPkl := oxPubKeyListXMLPubsubItemsItem.SelectElement("public-keys-list")
680 if oxPubKeyListXMLPubsubItemsItemPkl == nil {
681 return nil, fmt.Errorf("ox: no public-keys-list element")
682 }
683 oxPubKeyListXMLPubsubItemsItemPklPm := oxPubKeyListXMLPubsubItemsItemPkl.SelectElements("pubkey-metadata")
684 for _, r := range oxPubKeyListXMLPubsubItemsItemPklPm {
685 date := r.SelectAttr("date")
686 if date == nil {
687 continue
688 }
689 fingerprint := r.SelectAttr("v4-fingerprint")
690 if fingerprint == nil {
691 continue
692 }
693 keyDate, err := time.Parse(time.RFC3339, date.Value)
694 if err != nil {
695 return nil, fmt.Errorf("ox: get public keyring: failed to parse time stamp for key: %w", err)
696 }
697 if keyDate.After(newestKey) {
698 newestKey = keyDate
699 pubKeyRingID = fingerprint.Value
700 }
701 }
702 if pubKeyRingID == "none" {
703 return nil, fmt.Errorf("ox: server didn't provide public key fingerprints for %s", recipient)
704 }
705
706 pubKeyRingLocation, err := oxGetPubKeyLoc(recipient)
707 if err != nil {
708 return nil, fmt.Errorf("ox: get public keyring: failed to get public key ring location: %w", err)
709 }
710
711 pubKeyReadXML := etree.NewDocument()
712 err = pubKeyReadXML.ReadFromFile(pubKeyRingLocation)
713 if err == nil {
714 date := pubKeyReadXML.SelectElement("date")
715 if date != nil {
716 savedKeysDate, err := time.Parse(time.RFC3339, date.Text())
717 if err != nil {
718 return nil, fmt.Errorf("ox: get public keyring: failed to parse time for saved key: %w", err)
719 }
720 pubKey := pubKeyReadXML.SelectElements("pubkey")
721 if pubKey == nil {
722 return nil, fmt.Errorf("ox: couldn't read public key from cache")
723 }
724 keyByte, err := base64.StdEncoding.DecodeString(pubKey[0].Text())
725 if err != nil {
726 return nil, fmt.Errorf("ox: get public keyring: failed to decode saved key: %w", err)
727 }
728 key, err := crypto.NewKey(keyByte)
729 if err != nil {
730 return nil, fmt.Errorf("ox: get public keyring: failed to parse saved key: %w", err)
731 }
732 if !key.IsExpired(time.Now().Unix()) {
733 err = publicKeyRing.AddKey(key)
734 if err != nil {
735 return nil, fmt.Errorf("ox: get public keyring: failed to add key to public keyring: %w", err)
736 }
737 }
738 storedKeyFingerprint := strings.ToUpper(key.GetFingerprint())
739 if oxTrustMode != "blind" && storedKeyFingerprint != pubKeyRingID {
740 return nil, fmt.Errorf("ox: get public keyring: failed to use stored key %s for %s as server advertises %s but trust mode is set to \"%s\"",
741 storedKeyFingerprint, recipient, pubKeyRingID, oxTrustMode)
742 }
743 if !savedKeysDate.Before(newestKey) {
744 if publicKeyRing.CanEncrypt(time.Now().Unix()) {
745 return publicKeyRing, nil
746 }
747 }
748 } else if oxTrustMode != "blind" {
749 return nil, fmt.Errorf("ox: get public keyring: failed to parse date of store key for %s but trust mode is set to \"%s\"",
750 recipient, oxTrustMode)
751 }
752 }
753 pubKeyRing, err := oxRecvPublicKeys(client, iqc, recipient, pubKeyRingID)
754 if err != nil {
755 return nil, fmt.Errorf("ox: get public keyring: failed to get public keyring: %w", err)
756 }
757 pubKeySaveXML := etree.NewDocument()
758 date := pubKeySaveXML.CreateElement("date")
759 date.SetText(newestKey.Format(time.RFC3339))
760 for _, key := range pubKeyRing.GetKeys() {
761 keySerialized, err := key.Serialize()
762 if err != nil {
763 return nil, fmt.Errorf("ox: get public keyring: failed to serialize key: %w", err)
764 }
765 saveKey := pubKeySaveXML.CreateElement("pubkey")
766 saveKey.SetText(base64.StdEncoding.EncodeToString(keySerialized))
767 }
768 err = pubKeySaveXML.WriteToFile(pubKeyRingLocation)
769 if err != nil {
770 return nil, fmt.Errorf("ox: get public keyring: failed to create xml for saving public key: %w", err)
771 }
772 return pubKeyRing, nil
773 }
774
775 func oxEncrypt(client *xmpp.Client, oxPrivKey *crypto.Key, recipient string, keyRing crypto.KeyRing, message string, subject string, groupchat bool) (string, error) {
776 if message == "" {
777 return "", nil
778 }
779 ownJid := strings.Split(client.JID(), "/")[0]
780 if recipient != ownJid && !groupchat {
781 opk, err := oxPrivKey.GetPublicKey()
782 if err == nil {
783 ownKey, _ := crypto.NewKey(opk)
784 _ = keyRing.AddKey(ownKey)
785 }
786 }
787 oxCryptMessage := etree.NewDocument()
788 oxCryptMessage.WriteSettings.AttrSingleQuote = true
789 oxCryptMessageSc := oxCryptMessage.CreateElement("signcrypt")
790 oxCryptMessageSc.CreateAttr("xmlns", nsOx)
791 oxCryptMessageScTo := oxCryptMessageSc.CreateElement("to")
792 oxCryptMessageScTo.CreateAttr("jid", recipient)
793 oxCryptMessageScTime := oxCryptMessageSc.CreateElement("time")
794 oxCryptMessageScTime.CreateAttr("stamp", time.Now().UTC().Format("2006-01-02T15:04:05Z"))
795 oxCryptMessageScRpad := oxCryptMessageSc.CreateElement("rpad")
796 oxCryptMessageScRpad.CreateText(getRpad(len(message)))
797 oxCryptMessageScPayload := oxCryptMessageSc.CreateElement("payload")
798 if subject != "" {
799 oxCryptMessageScPayloadSub := oxCryptMessageScPayload.CreateElement("subject")
800 oxCryptMessageScPayloadSub.CreateText(subject)
801 }
802 oxCryptMessageScPayloadBody := oxCryptMessageScPayload.CreateElement("body")
803 oxCryptMessageScPayloadBody.CreateAttr("xmlns", nsJabberClient)
804 oxCryptMessageScPayloadBody.CreateText(message)
805 ocm, err := oxCryptMessage.WriteToString()
806 if err != nil {
807 return strError, fmt.Errorf("ox: encrypt: failed to create xml for ox crypt message: %w", err)
808 }
809 pgpEncrypt, err := crypto.PGP().Encryption().
810 Recipients(&keyRing).
811 SigningKey(oxPrivKey).New()
812 if err != nil {
813 return strError, fmt.Errorf("oxEncrypt: failed to create pgp encryption interface: %w", err)
814 }
815 pgpMessage, err := pgpEncrypt.Encrypt([]byte(ocm))
816 if err != nil {
817 return strError, fmt.Errorf("ox: encrypt: failed to create pgp message: %w", err)
818 }
819 id := getID()
820 om := etree.NewDocument()
821 om.WriteSettings.AttrSingleQuote = true
822 omMessage := om.CreateElement("message")
823 omMessage.CreateAttr("to", recipient)
824 omMessage.CreateAttr("id", id)
825 if groupchat {
826 omMessage.CreateAttr("type", "groupchat")
827 }
828 omMessageStore := omMessage.CreateElement("store")
829 omMessageStore.CreateAttr("xmlns", nsHints)
830 omMessageEme := omMessage.CreateElement("encryption")
831 omMessageEme.CreateAttr("xmlns", nsEme)
832 omMessageEme.CreateAttr("namespace", nsOx)
833 omMessageOpgp := omMessage.CreateElement("openpgp")
834 omMessageOpgp.CreateAttr("xmlns", nsOx)
835 omMessageOpgp.CreateText(base64.StdEncoding.EncodeToString(pgpMessage.Bytes()))
836 omMessageBody := omMessage.CreateElement("body")
837 omMessageBody.CreateText(oxAltBody)
838 omMessageOrigID := omMessage.CreateElement("origin-id")
839 omMessageOrigID.CreateAttr("xmlns", nsSid)
840 omMessageOrigID.CreateAttr("id", id)
841 oms, err := om.WriteToString()
842 if err != nil {
843 return strError, fmt.Errorf("ox: encrypt: failed to create xml for ox message: %w", err)
844 }
845
846 return oms, nil
847 }
848
849 func oxGetPublicKeyRingChatroom(client *xmpp.Client, iqc chan xmpp.IQ, drc chan xmpp.DiscoResult,
850 chatroom string, oxTrustMode string,
851 ) (*crypto.KeyRing, error) {
852 keyRing, err := crypto.NewKeyRing(nil)
853 if err != nil {
854 return nil, err
855 }
856 discoResult, err := getDiscoInfo(client, drc, chatroom)
857 if err != nil {
858 return nil, fmt.Errorf("ox: %w", err)
859 }
860 nonAnon := false
861 for _, feature := range discoResult.Features {
862 if feature == "muc_nonanonymous" {
863 nonAnon = true
864 }
865 }
866 if !nonAnon {
867 return nil, fmt.Errorf("ox: muc is not nonanonymous")
868 }
869 affiliations := [3]string{"admin", "owner", "member"}
870 for _, affiliation := range affiliations {
871 memberlistRequest := etree.NewDocument()
872 query := memberlistRequest.CreateElement("query")
873 query.CreateAttr("xmlns", nsMUCAdmin)
874 item := query.CreateElement("item")
875 item.CreateAttr("affiliation", affiliation)
876 mlr, err := memberlistRequest.WriteToString()
877 if err != nil {
878 return nil, err
879 }
880 iqReply, err := sendIQ(client, iqc, chatroom, "get", mlr)
881 if err != nil {
882 return nil, err
883 }
884 memberlist := etree.NewDocument()
885 err = memberlist.ReadFromBytes(iqReply.Query)
886 if err != nil {
887 return nil, err
888 }
889 query = memberlist.SelectElement("query")
890 if query == nil {
891 return nil, fmt.Errorf("ox: error during disco info query")
892 }
893 items := query.SelectElements("item")
894 if items == nil {
895 continue
896 }
897 for _, item := range items {
898 jid := item.SelectAttr("jid")
899 if jid == nil {
900 continue
901 }
902 memberKeyRing, err := oxGetPublicKeyRing(client, iqc, jid.Value, oxTrustMode)
903 if err != nil {
904 continue
905 }
906 for _, key := range memberKeyRing.GetKeys() {
907 err = keyRing.AddKey(key)
908 if err != nil {
909 continue
910 }
911 }
912 }
913 }
914 if keyRing == nil {
915 return nil, fmt.Errorf("ox: didn't receive public keys for muc members")
916 }
917 return keyRing, nil
918 }
919
920 func oxCheckPrivKeyNode(jid string, client *xmpp.Client, iqc chan xmpp.IQ) (xmpp.IQ, error) {
921 slog.Info("ox: parsing private key request to IQ")
922 recvPrivKeyRequest := etree.NewDocument()
923 recvPrivKeyRequest.WriteSettings.AttrSingleQuote = true
924 rpkrPubsub := recvPrivKeyRequest.CreateElement("pubsub")
925 rpkrPubsub.CreateAttr("xmlns", nsPubsub)
926 rpkrItems := rpkrPubsub.CreateElement("items")
927 rpkrItems.CreateAttr("node", nsOxSecretKey)
928 rpkrItems.CreateAttr("max_items", "1")
929 rpkr, err := recvPrivKeyRequest.WriteToString()
930 if err != nil {
931 return xmpp.IQ{}, fmt.Errorf("ox: check private key node: failed to create private key request: %w", err)
932 }
933 slog.Info("ox: sending IQ to request private key", "node", nsOxSecretKey)
934 oxPrivKeyReply, err := sendIQ(client, iqc, jid, "get", rpkr)
935 if err != nil {
936 return xmpp.IQ{}, fmt.Errorf("ox: check private key node: failed parsing iq reply to private key request: %w", err)
937 }
938 if oxPrivKeyReply.Type != strResult {
939 slog.Info("ox: received iq reply", "error", oxPrivKeyReply.Error.Condition)
940 if oxPrivKeyReply.Error.Condition == "item-not-found" {
941 slog.Info("ox: creating pep node")
942 createPrivKeyNodeRequest := etree.NewDocument()
943 createPrivKeyNodeRequest.WriteSettings.AttrSingleQuote = true
944 cpnrPubsub := createPrivKeyNodeRequest.CreateElement("pubsub")
945 cpnrPubsub.CreateAttr("xmlns", nsPubsub)
946 cpnrCreate := cpnrPubsub.CreateElement("create")
947 cpnrCreate.CreateAttr("node", nsOxSecretKey)
948 cpnrConfigure := cpnrPubsub.CreateElement("configure")
949 cpnrX := cpnrConfigure.CreateElement("x")
950 cpnrX.CreateAttr("xmlns", nsJabberData)
951 cpnrX.CreateAttr("type", "submit")
952 cpnrField1 := cpnrX.CreateElement("field")
953 cpnrField1.CreateAttr("var", "FORM_TYPE")
954 cpnrField1.CreateAttr("type", "hidden")
955 cpnrField1Val := cpnrField1.CreateElement("value")
956 cpnrField1Val.CreateText(pubsubNodeConfig)
957 cpnrField2 := cpnrX.CreateElement("field")
958 cpnrField2.CreateAttr("var", "pubsub#access_model")
959 cpnrField2Val := cpnrField2.CreateElement("value")
960 cpnrField2Val.CreateText("whitelist")
961 cpnrField3 := cpnrX.CreateElement("field")
962 cpnrField3.CreateAttr("var", "pubsub#send_last_published_item")
963 cpnrField3Val := cpnrField3.CreateElement("value")
964 cpnrField3Val.CreateText("on_sub")
965 cpnr, err := createPrivKeyNodeRequest.WriteToString()
966 if err != nil {
967 return xmpp.IQ{}, fmt.Errorf("ox: failed to create private key node: %w", err)
968 }
969 slog.Info("ox: sending IQ to create private key node", "node", nsOxSecretKey)
970 oxCreateNodeReply, err := sendIQ(client, iqc, jid, "set", cpnr)
971 if err != nil {
972 return xmpp.IQ{}, fmt.Errorf("ox: create private key node: failed parsing iq reply to private key node creation request: %w", err)
973 }
974 if oxCreateNodeReply.Type != strResult {
975 return xmpp.IQ{}, fmt.Errorf("ox: failed to create private key node: %s", oxCreateNodeReply.Error)
976 }
977
978 }
979 }
980 return oxPrivKeyReply, nil
981 }
982
983 func oxRecvPrivKey(jid string, secret string, client *xmpp.Client, iqc chan xmpp.IQ, drc chan xmpp.DiscoResult,
984 oxTrustMode string,
985 ) error {
986 err := checkPEPsupport(jid, client, iqc, drc)
987 if err != nil {
988 return fmt.Errorf("ox: receive private key: %w", err)
989 }
990 oxPrivKeyReply, err := oxCheckPrivKeyNode(jid, client, iqc)
991 if err != nil {
992 return fmt.Errorf("ox: receive private key: %w", err)
993 }
994 slog.Info("ox: receiving private key: received result")
995 slog.Info("ox: receiving private key: receiving own private key from pubsub")
996 oxPrivKeyXML := etree.NewDocument()
997 err = oxPrivKeyXML.ReadFromBytes(oxPrivKeyReply.Query)
998 if err != nil {
999 return fmt.Errorf("ox: receive private key: failed parsing iq reply to private key request: %w", err)
1000 }
1001 oxPrivKeyXMLPubsub := oxPrivKeyXML.SelectElement("pubsub")
1002 if oxPrivKeyXMLPubsub == nil {
1003 return fmt.Errorf("ox: receive private key: no pubsub element in reply to private key request")
1004 }
1005 oxPrivKeyXMLItems := oxPrivKeyXMLPubsub.SelectElement("items")
1006 if oxPrivKeyXMLItems == nil {
1007 return fmt.Errorf("ox: receive private key: no items element in reply to private key request")
1008 }
1009 oxPrivKeyXMLItemsNode := oxPrivKeyXMLItems.SelectAttr("node")
1010 if oxPrivKeyXMLItemsNode.Value != nsOxSecretKey {
1011 return fmt.Errorf("ox: receive private key: wrong node: %s instead of %s", oxPrivKeyXMLItemsNode.Value, nsOxSecretKey)
1012 }
1013 oxPrivKeyXMLItem := oxPrivKeyXMLItems.SelectElement("item")
1014 if oxPrivKeyXMLItem == nil {
1015 return fmt.Errorf("ox: receive private key: no item element in reply to private key request")
1016 }
1017 oxPrivKeyXMLSecretKey := oxPrivKeyXMLItem.SelectElement("secretkey")
1018 if oxPrivKeyXMLSecretKey == nil {
1019 return fmt.Errorf("ox: receive private key: no secretkey element in reply to private key request")
1020 }
1021 if oxPrivKeyXMLSecretKey.NamespaceURI() != nsOx {
1022 return fmt.Errorf("ox: receive private key: wrong namespace: %s instead of %s", oxPrivKeyXMLSecretKey.NamespaceURI(), nsOx)
1023 }
1024 decodedPrivKey, err := base64.StdEncoding.DecodeString(oxPrivKeyXMLSecretKey.Text())
1025 if err != nil {
1026 return fmt.Errorf("ox: receive private key: failed to decode private key: %w", err)
1027 }
1028 pgpDecrypt, err := crypto.PGP().
1029 Decryption().
1030 Password([]byte(secret)).
1031 New()
1032 if err != nil {
1033 return fmt.Errorf("ox: receive private key: failed to decode private key: %w", err)
1034 }
1035 oxPrivKey, err := pgpDecrypt.Decrypt(decodedPrivKey, crypto.Bytes)
1036 if err != nil {
1037 return fmt.Errorf("ox receive private key: failed to decrypt private key: %w", err)
1038 }
1039 location, err := oxGetPrivKeyLoc(jid)
1040 if err != nil {
1041 return fmt.Errorf("ox: receive private key: failed to determine private key location: %w", err)
1042 }
1043 slog.Info("ox: receive private key: getting private key location", "jid", jid, "location", location)
1044 key, err := crypto.NewKey(oxPrivKey.Bytes())
1045 if err != nil {
1046 return fmt.Errorf("ox: receive private key: failed to read private key: %w", err)
1047 }
1048 keySerialized, err := key.Serialize()
1049 if err != nil {
1050 return fmt.Errorf("ox: receive private key: failed to serialize private key: %w", err)
1051 }
1052 err = oxStoreKey(location, base64.StdEncoding.EncodeToString(keySerialized))
1053 if err != nil {
1054 return fmt.Errorf("ox: receive private key: failed to store private key: %w", err)
1055 }
1056 slog.Info("ox: receive private key: requesting public key ring")
1057 fingerprint := key.GetFingerprint()
1058 pubKeyRing, err := oxGetPublicKeyRing(client, iqc, jid, oxTrustMode)
1059 if err == nil {
1060 slog.Info("ox: receive private key: checking if public key ring contains", "fingerprint", fingerprint)
1061 pubKeys := pubKeyRing.GetKeys()
1062 for _, r := range pubKeys {
1063 fp := strings.ToUpper(r.GetFingerprint())
1064 slog.Info("ox: receive private key: checking", "fingerprint", fp)
1065 if fp == fingerprint {
1066 slog.Info("ox: receive private key: checking if public key ring contains fingerprint: success")
1067 return nil
1068 }
1069 }
1070 }
1071 pk, err := key.GetPublicKey()
1072 if err != nil {
1073 return fmt.Errorf("ox: receive private key: failed to derive public key: %w", err)
1074 }
1075 pubKey, err := crypto.NewKey(pk)
1076 if err != nil {
1077 return fmt.Errorf("ox: receive private key: failed to serialize public key: %w", err)
1078 }
1079 slog.Info("ox: import private key: publishing public key")
1080 err = oxPublishPubKey(jid, client, iqc, pubKey)
1081 if err != nil {
1082 return fmt.Errorf("ox: receive private key: failed to publish public key: %w", err)
1083 }
1084 return nil
1085 }
1086
1087 func oxTransPrivKey(jid string, oxPrivKey *crypto.Key, client *xmpp.Client, iqc chan xmpp.IQ, drc chan xmpp.DiscoResult) error {
1088 err := checkPEPsupport(jid, client, iqc, drc)
1089 if err != nil {
1090 return fmt.Errorf("ox: transfer private key: %w", err)
1091 }
1092 slog.Info("ox: transferring private key: generating secret")
1093 secret, err := getSecret(oxSecretAlphabet, oxSecretLength, oxSecretChunkSize)
1094 if err != nil {
1095 return fmt.Errorf("ox: transfer private key: failed to get secret: %w", err)
1096 }
1097 slog.Info("ox: transferring private key: creating encryption interface")
1098 pgpEncrypt, err := crypto.PGP().
1099 Encryption().
1100 Password([]byte(secret)).
1101 New()
1102 if err != nil {
1103 return fmt.Errorf("ox: transfer private key: failed to create pgp encryption interface: %w", err)
1104 }
1105 slog.Info("ox: transferring private key: serializing private key")
1106 oxPrivKeySerialized, err := oxPrivKey.Serialize()
1107 if err != nil {
1108 return fmt.Errorf("ox: transfer private key: failed to serialize private key: %w", err)
1109 }
1110 slog.Info("ox: transferring private key: encrypting private key")
1111 pgpMessage, err := pgpEncrypt.Encrypt(oxPrivKeySerialized)
1112 if err != nil {
1113 return fmt.Errorf("ox: transfer private key: failed to create pgp message: %w", err)
1114 }
1115 _, err = oxCheckPrivKeyNode(jid, client, iqc)
1116 if err != nil {
1117 return fmt.Errorf("ox: transfer private key: %w", err)
1118 }
1119 slog.Info("ox: publishing private key")
1120 publishPrivKeyRequest := etree.NewDocument()
1121 publishPrivKeyRequest.WriteSettings.AttrSingleQuote = true
1122 ppkrPubsub := publishPrivKeyRequest.CreateElement("pubsub")
1123 ppkrPubsub.CreateAttr("xmlns", nsPubsub)
1124 ppkrPublish := ppkrPubsub.CreateElement("publish")
1125 ppkrPublish.CreateAttr("node", nsOxSecretKey)
1126 ppkrItem := ppkrPublish.CreateElement("item")
1127 ppkrSecretKey := ppkrItem.CreateElement("secretkey")
1128 ppkrSecretKey.CreateAttr("xmlns", nsOx)
1129 ppkrSecretKey.CreateText(base64.StdEncoding.EncodeToString(pgpMessage.Bytes()))
1130 ppkr, err := publishPrivKeyRequest.WriteToString()
1131 if err != nil {
1132 return fmt.Errorf("ox: failed to create private key publish request: %w", err)
1133 }
1134 slog.Info("ox: sending IQ to publish private key")
1135 oxPublishPrivateKeyReply, err := sendIQ(client, iqc, jid, "set", ppkr)
1136 if err != nil {
1137 return fmt.Errorf("ox: publish private key: failed parsing iq reply to publish private key request: %w", err)
1138 }
1139 if oxPublishPrivateKeyReply.Type != strResult {
1140 return fmt.Errorf("ox: publish private key: %s", oxPublishPrivateKeyReply.Error.Condition)
1141 }
1142 fmt.Printf("OX: Secret key published: Encrypted with the secret phrase: %s\n", secret)
1143 return nil
1144 }