File: ox.go

package info (click to toggle)
go-sendxmpp 0.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 332 kB
  • sloc: makefile: 11
file content (842 lines) | stat: -rw-r--r-- 31,537 bytes parent folder | download | duplicates (2)
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
// Copyright Martin Dosch.
// Use of this source code is governed by the BSD-2-clause
// license that can be found in the LICENSE file.

// TODO: Add more logging
package main

import (
	"encoding/base64"
	"fmt"
	"io"
	"log"
	"log/slog"
	"os"
	"runtime"
	"strings"
	"time"

	"github.com/ProtonMail/gopenpgp/v3/crypto" // MIT License
	"github.com/beevik/etree"                  // BSD-2-clause
	"github.com/xmppo/go-xmpp"                 // BSD-3-Clause
)

func oxDeleteNodes(jid string, client *xmpp.Client, iqc chan xmpp.IQ) error {
	nodeListRequest := etree.NewDocument()
	nodeListRequest.WriteSettings.AttrSingleQuote = true
	query := nodeListRequest.CreateElement("query")
	query.CreateAttr("xmlns", nsDiscoItems)
	nlr, err := nodeListRequest.WriteToString()
	if err != nil {
		return fmt.Errorf("ox: delete nodes: failed to create node list request %w", err)
	}
	slog.Info("ox: sending IQ to list pep nodes")
	iqReply, err := sendIQ(client, iqc, jid, "get", nlr)
	if err != nil {
		return fmt.Errorf("ox: delete nodes: failure with node list request iq: %w", err)
	}
	slog.Info("ox: parsing reply to IQ")
	nodeListReply := etree.NewDocument()
	err = nodeListReply.ReadFromBytes(iqReply.Query)
	if err != nil {
		return fmt.Errorf("ox: delete nodes: failed to read node list reply iq: %w", err)
	}
	query = nodeListReply.SelectElement("query")
	if query == nil {
		return fmt.Errorf("ox: error parsing iq reply")
	}
	items := query.SelectElements("item")
	if items == nil {
		return fmt.Errorf("ox: error parsing iq reply")
	}
	for _, item := range items {
		node := item.SelectAttr("node")
		if node == nil {
			continue
		}
		if !strings.Contains(node.Value, nsOx) {
			continue
		}
		deleteNodeRequest := etree.NewDocument()
		deleteNodeRequest.WriteSettings.AttrSingleQuote = true
		pubsub := deleteNodeRequest.CreateElement("pubsub")
		pubsub.CreateAttr("xmlns", nsPubsubOwner)
		del := pubsub.CreateElement("delete")
		del.CreateAttr("node", node.Value)
		dnr, err := deleteNodeRequest.WriteToString()
		if err != nil {
			continue
		}
		slog.Info("ox: sending IQ to list pep nodes", "node", node.Value)
		_, err = sendIQ(client, iqc, jid, "set", dnr)
		if err != nil {
			continue
		}
	}
	return nil
}

func oxDecrypt(m xmpp.Chat, client *xmpp.Client, iqc chan xmpp.IQ, user string, oxPrivKey *crypto.Key) (string, time.Time, error) {
	var cryptMsgByte []byte
	var err error
	sender := strings.Split(m.Remote, "/")[0]
	for _, r := range m.OtherElem {
		if r.XMLName.Space == nsOx {
			cryptMsgByte, err = base64.StdEncoding.DecodeString(r.InnerXML)
			if err != nil {
				return strError, time.Now(), err
			}
			break
		}
	}
	oxMsg := crypto.NewPGPMessage(cryptMsgByte)
	keyRing, err := crypto.NewKeyRing(oxPrivKey)
	if err != nil {
		return strError, time.Now(), err
	}
	slog.Info("ox: decrypting: getting senders key", "sender", sender)
	senderKeyRing, err := oxGetPublicKeyRing(client, iqc, sender)
	if err != nil {
		return strError, time.Now(), err
	}
	slog.Info("ox: decrypting message")
	pgpDecrypt, err := crypto.PGP().Decryption().
		DecryptionKeys(keyRing).
		VerificationKeys(senderKeyRing).
		New()
	if err != nil {
		return strError, time.Now(), err
	}
	decryptMsg, err := pgpDecrypt.Decrypt(oxMsg.Bytes(), crypto.Bytes)
	if err != nil {
		return strError, time.Now(), err
	}
	// Remove invalid code points.
	slog.Info("ox: removing invalid code points from decrypted message")
	message := validUTF8(decryptMsg.String())
	doc := etree.NewDocument()
	err = doc.ReadFromString(message)
	if err != nil {
		return strError, time.Now(), err
	}
	slog.Info("ox: decrypting: checking signcrypt element")
	signcrypt := doc.SelectElement("signcrypt")
	if signcrypt == nil {
		return strError, time.Now(), fmt.Errorf("ox: no signcrypt element")
	}
	slog.Info("ox: decrypting: checking to element")
	to := signcrypt.SelectElement("to")
	if to == nil {
		return strError, time.Now(), fmt.Errorf("ox: no to element")
	}
	slog.Info("ox: decrypting: checking jid attribute")
	jid := to.SelectAttr("jid")
	if jid == nil {
		return strError, time.Now(), fmt.Errorf("ox: no jid attribute")
	}
	jidAttrib := strings.Split(jid.Value, "/")[0]
	slog.Info("ox: decrypting: comparing jid attribute with local user",
		"jid-attribute", jidAttrib, "user", user)
	if jidAttrib != user {
		return strError, time.Now(), fmt.Errorf("ox: encrypted for wrong user")
	}
	slog.Info("ox: decrypting: checking time element")
	timestamp := signcrypt.SelectElement("time")
	if timestamp == nil {
		return strError, time.Now(), fmt.Errorf("ox: no time element")
	}
	slog.Info("ox: decrypting: checking stamp attribute")
	stamp := timestamp.SelectAttr("stamp")
	if stamp == nil {
		return strError, time.Now(), fmt.Errorf("ox: no stamp attribute")
	}
	slog.Info("ox: decrypting: parsing time stamp")
	msgStamp, err := time.Parse("2006-01-02T15:04:05Z0700", stamp.Value)
	if err != nil {
		return strError, time.Now(), err
	}
	slog.Info("ox: decrypting: checking payload element")
	payload := signcrypt.SelectElement("payload")
	if payload == nil {
		return strError, time.Now(), fmt.Errorf("ox: no payload element")
	}
	slog.Info("ox: decrypting: checking body element")
	body := payload.SelectElement("body")
	if body == nil {
		return "", time.Now(), nil
	}
	slog.Info("ox: decrypting: returning body")
	return body.Text(), msgStamp, nil
}

func isOxMsg(m xmpp.Chat) bool {
	slog.Info("ox: checking for ox message")
	for _, r := range m.OtherElem {
		slog.Info("ox: checking for ox message: comparing", "XMLNameSpace", r.XMLName.Space,
			"OXNameSpace", nsOx)
		if r.XMLName.Space == nsOx {
			slog.Info("ox: checking for ox message:", "result", true)
			return true
		}
	}
	slog.Info("ox: checking for ox message:", "result", false)
	return false
}

func oxImportPrivKey(jid string, privKeyLocation string, client *xmpp.Client, iqc chan xmpp.IQ) error {
	xmppURI := "xmpp:" + jid
	slog.Info("ox: importing private key:", "xmpp-uri", xmppURI)
	slog.Info("ox: importing private key:", "location", privKeyLocation)
	buffer, err := readFile(privKeyLocation)
	if err != nil {
		return err
	}
	slog.Info("ox: importing private key: reading key")
	key, err := crypto.NewKey(buffer.Bytes())
	if err != nil {
		slog.Info("ox: importing private key: reading key failed: checking if armored")
		key, err = crypto.NewKeyFromArmored(buffer.String())
		if err != nil {
			keyDecoded, err := base64.StdEncoding.DecodeString(buffer.String())
			slog.Info("ox: importing private key: reading key failed: checking if base64 encoded")
			if err != nil {
				return fmt.Errorf("ox: import privkey: failed to import private key: %w", err)
			}
			slog.Info("ox: importing private key: reading key")
			key, err = crypto.NewKey(keyDecoded)
			if err != nil {
				return fmt.Errorf("ox: import privkey: failed to import private key: %w", err)
			}
		}
	}
	slog.Info("ox: importing private key: reading key: success")
	entity := key.GetEntity()
	slog.Info("ox: importing private key:", "entity", entity)
	if entity.Identities[xmppURI] == nil {
		return fmt.Errorf("ox: key identity is not %s", xmppURI)
	}
	slog.Info("ox: importing private key: deriving public key")
	pk, err := key.GetPublicKey()
	if err != nil {
		return fmt.Errorf("ox: import privkey: failed to get public key associated to private key: %w", err)
	}
	pubKey, err := crypto.NewKey(pk)
	if err != nil {
		return fmt.Errorf("ox: import privkey: failed to get public key associated to private key: %w", err)
	}
	fingerprint := strings.ToUpper(pubKey.GetFingerprint())
	slog.Info("ox: importing private key:", "fingerprint", fingerprint)
	slog.Info("ox: importing private key: checking if public key is already published")
	_, err = oxRecvPublicKeys(client, iqc, jid, fingerprint)
	if err != nil {
		slog.Info("ox: importing private key: publishing public key")
		err = oxPublishPubKey(jid, client, iqc, pubKey)
		if err != nil {
			return fmt.Errorf("ox: import privkey: failed to publish public key: %w", err)
		}
	}
	location, err := oxGetPrivKeyLoc(jid)
	if err != nil {
		return fmt.Errorf("ox: import privkey: failed to determine private key location: %w", err)
	}
	slog.Info("ox: importing private key: getting private key location", "jid", jid, "location", location)
	slog.Info("ox: importing private key: serializing key")
	keySerialized, err := key.Serialize()
	if err != nil {
		return fmt.Errorf("ox: import privkey: failed to serialize private key: %w", err)
	}
	slog.Info("ox: importing private key: storing key:", "location", location)
	err = oxStoreKey(location,
		base64.StdEncoding.EncodeToString(keySerialized))
	if err != nil {
		log.Fatal(err)
	}
	slog.Info("ox: importing private key: requesting public key ring")
	pubKeyRing, err := oxGetPublicKeyRing(client, iqc, jid)
	if err == nil {
		slog.Info("ox: importing private key: checking if public key ring contains", "fingerprint", fingerprint)
		pubKeys := pubKeyRing.GetKeys()
		for _, r := range pubKeys {
			fp := strings.ToUpper(r.GetFingerprint())
			slog.Info("ox: importing private key: checking", "fingerprint", fp)
			if fp == fingerprint {
				slog.Info("ox: importing private key: checking if public key ring contains fingerprint: success")
				return nil
			}
		}
	}
	slog.Info("ox: importing private key: publishing public key")
	err = oxPublishPubKey(jid, client, iqc, pubKey)
	if err != nil {
		return fmt.Errorf("ox: import privkey: failed to publish public key: %w", err)
	}
	return nil
}

func oxPublishPubKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ, pubKey *crypto.Key) error {
	keyCreated := time.Now().UTC().Format("2006-01-02T15:04:05Z")
	fingerprint := strings.ToUpper(pubKey.GetFingerprint())
	slog.Info("ox: publishing public key:", "fingerprint", fingerprint, "created", keyCreated)
	slog.Info("ox: publishing public key: serializing public key")
	keySerialized, err := pubKey.Serialize()
	if err != nil {
		return fmt.Errorf("ox: publish pubkey: failed to serialize pubkey: %w", err)
	}
	slog.Info("ox: publishing public key: base64 encoding public key")
	pubKeyBase64 := base64.StdEncoding.EncodeToString(keySerialized)
	root := etree.NewDocument()
	root.WriteSettings.AttrSingleQuote = true
	pubsub := root.CreateElement("pubsub")
	pubsub.CreateAttr("xmlns", nsPubsub)
	publish := pubsub.CreateElement("publish")
	publish.CreateAttr("node", nsOxPubKeys+":"+fingerprint)
	item := publish.CreateElement("item")
	item.CreateAttr("id", keyCreated)
	pubkey := item.CreateElement("pubkey")
	pubkey.CreateAttr("xmlns", nsOx)
	data := pubkey.CreateElement("data")
	data.CreateText(pubKeyBase64)
	publishoptions := pubsub.CreateElement("publish-options")
	x := publishoptions.CreateElement("x")
	x.CreateAttr("xmlns", nsJabberData)
	x.CreateAttr("type", "submit")
	field := x.CreateElement("field")
	field.CreateAttr("var", "FORM_TYPE")
	field.CreateAttr("type", "hidden")
	value := field.CreateElement("value")
	value.CreateText(pubsubPubOptions)
	field = x.CreateElement("field")
	field.CreateAttr("var", "pubsub#access_model")
	value = field.CreateElement("value")
	value.CreateText("open")
	xmlstring, err := root.WriteToString()
	if err != nil {
		return fmt.Errorf("ox: publish pubkey: failed to create publish public key iq xml: %w", err)
	}
	slog.Info("ox: publishing public key: sending IQ")
	iqReply, err := sendIQ(client, iqc, jid, "set", xmlstring)
	if err != nil {
		return fmt.Errorf("ox: publish pubkey: iq failure publishing public key: %w", err)
	}
	if iqReply.Type != strResult {
		return fmt.Errorf("ox: error while publishing public key")
	}
	slog.Info("ox: publishing public key: received result")
	slog.Info("ox: publishing public key: receiving own public key from pubsub")
	ownPubKeyRingFromPubsub, err := oxRecvPublicKeys(client, iqc, jid, fingerprint)
	if err != nil {
		return fmt.Errorf("ox: couldn't successfully verify public key upload")
	}
	ownPubKeyFromPubsub := ownPubKeyRingFromPubsub.GetKeys()[0]
	slog.Info("ox: publishing public key: serializing own public key received from pubsub")
	ownPubKeyFromPubsubSerialized, err := ownPubKeyFromPubsub.Serialize()
	if err != nil {
		return fmt.Errorf("ox: couldn't successfully verify public key upload")
	}
	slog.Info("ox: publishing public key: base64 encoding own public key received from pubsub")
	psPubKeyBase64 := base64.StdEncoding.EncodeToString(ownPubKeyFromPubsubSerialized)
	slog.Info("ox: publishing public key: comparing local and pubsub public key:", "local", pubKeyBase64, "pubsub", psPubKeyBase64)
	if pubKeyBase64 != psPubKeyBase64 {
		return fmt.Errorf("ox: couldn't successfully verify public key upload")
	}
	slog.Info("ox: publishing public key: comparing local and pubsub public key: success")
	root = etree.NewDocument()
	root.WriteSettings.AttrSingleQuote = true
	pubsub = root.CreateElement("pubsub")
	pubsub.CreateAttr("xmlns", nsPubsub)
	publish = pubsub.CreateElement("publish")
	publish.CreateAttr("node", nsOxPubKeys)
	item = publish.CreateElement("item")
	pubkeyslist := item.CreateElement("public-keys-list")
	pubkeyslist.CreateAttr("xmlns", nsOx)
	pubkeymeta := pubkeyslist.CreateElement("pubkey-metadata")
	pubkeymeta.CreateAttr("v4-fingerprint", fingerprint)
	pubkeymeta.CreateAttr("date", keyCreated)
	publishoptions = pubsub.CreateElement("publish-options")
	x = publishoptions.CreateElement("x")
	x.CreateAttr("xmlns", nsJabberData)
	x.CreateAttr("type", "submit")
	field = x.CreateElement("field")
	field.CreateAttr("var", "FORM_TYPE")
	field.CreateAttr("type", "hidden")
	value = field.CreateElement("value")
	value.CreateText(pubsubPubOptions)
	field = x.CreateElement("field")
	field.CreateAttr("var", "pubsub#access_model")
	value = field.CreateElement("value")
	value.CreateText("open")
	xmlstring, err = root.WriteToString()
	if err != nil {
		return fmt.Errorf("ox: publish pubkey: failed to create xml for iq to publish public key list: %w", err)
	}
	slog.Info("ox: publishing public key: sending IQ to publish key list to pubsub")
	iqReply, err = sendIQ(client, iqc, jid, "set", xmlstring)
	if err != nil {
		return fmt.Errorf("ox: publish pubkey: iq failure publishing public key list: %w", err)
	}
	if iqReply.Type != strResult {
		return fmt.Errorf("ox: couldn't publish public key list")
	}
	slog.Info("ox: publishing public key: received result")
	return nil
}

func oxGetPrivKeyLoc(jid string) (string, error) {
	dataDir, err := getDataPath(fsFriendlyJid(jid), true)
	slog.Info("ox: get private key location: trying", "location", dataDir)
	if err != nil {
		return strError, fmt.Errorf("ox: get privkey location: %w", err)
	}
	oldDataDir, err := getDataPath("oxprivkeys/", false)
	slog.Info("ox: get private key location: trying", "location", oldDataDir)
	if err != nil {
		return strError, fmt.Errorf("ox: get privkey location: %w", err)
	}
	// TODO: Remove handling of oldDataFile in a later version when it's very likely that there are no
	// more versions in use using the oldDataFile (<0.8.3).
	oldDataFile := oldDataDir + base64.StdEncoding.EncodeToString([]byte(jid))
	oldDataFile2 := oldDataDir + strings.ReplaceAll(jid, "@", "_at_")
	oldDataFile3 := oldDataDir + fsFriendlyJid(jid)
	dataFile := dataDir + "oxprivkey"
	if _, err := os.Stat(oldDataFile); err == nil {
		err := os.Rename(oldDataFile, dataFile)
		slog.Info("ox: get private key location: moving file to new location", "old", oldDataFile, "new", dataFile)
		if err != nil {
			return dataFile, err
		}
	}
	if _, err := os.Stat(oldDataFile2); err == nil {
		slog.Info("ox: get private key location: moving file to new location", "old", oldDataFile2, "new", dataFile)
		err := os.Rename(oldDataFile2, dataFile)
		if err != nil {
			return dataFile, err
		}
	}
	if _, err := os.Stat(oldDataFile3); err == nil {
		slog.Info("ox: get private key location: moving file to new location", "old", oldDataFile3, "new", dataFile)
		err := os.Rename(oldDataFile3, dataFile)
		if err != nil {
			return dataFile, err
		}
	}
	dir, err := os.Open(oldDataDir)
	if err == nil {
		slog.Info("ox: get private key location: entering old data", "folder", oldDataDir)
		slog.Info("ox: get private key location: checking if directory is empty")
		_, err = dir.ReadDir(1)
		// Delete old data dir if empty.
		if err == io.EOF {
			slog.Info("ox: get private key location: trying to delete empty", "folder", oldDataDir)
			err = os.Remove(oldDataDir)
			if err != nil {
				fmt.Printf("oxGetPrivKeyLoc: failed to delete old private key location: %v\n", err)
			}
		}
	}
	return dataFile, nil
}

func oxGetPubKeyLoc(fingerprint string) (string, error) {
	dataDir, err := getDataPath("oxpubkeys/", true)
	slog.Info("ox: getting public key", "location", dataDir)
	if err != nil {
		return strError, fmt.Errorf("ox: get pubkey location: %w", err)
	}
	dataFile := dataDir + fingerprint
	slog.Info("ox: getting public key location", "file", dataFile)
	return dataFile, nil
}

func oxGetPrivKey(jid string, passphrase string) (*crypto.Key, error) {
	dataFile, err := oxGetPrivKeyLoc(jid)
	if err != nil {
		log.Fatal(err)
	}
	slog.Info("ox: getting private key:", "file", dataFile)
	keyBuffer, err := readFile(dataFile)
	if err != nil {
		log.Fatal(err)
	}
	keyString := keyBuffer.String()
	slog.Info("ox: getting private key: base64 decoding key")
	decodedPrivKey, err := base64.StdEncoding.DecodeString(keyString)
	if err != nil {
		return nil, fmt.Errorf("ox: get privkey: failed to decode private key: %w", err)
	}
	slog.Info("ox: getting private key: decoding key")
	key, err := crypto.NewKey(decodedPrivKey)
	if err != nil {
		return nil, fmt.Errorf("ox: get privkey: failed to decode private key: %w", err)
	}
	if passphrase != "" {
		slog.Info("ox: getting private key: unlocking key", "passphrase", "REDACTED")
		key, err = key.Unlock([]byte(passphrase))
		if err != nil {
			log.Fatal("ox: couldn't unlock private key")
		}
	}
	isLocked, err := key.IsLocked()
	if err != nil {
		return nil, fmt.Errorf("ox: get privkey: failed to check whether private key is locked: %w", err)
	}
	if isLocked {
		log.Fatal("ox: private key is locked")
	}
	slog.Info("ox: getting private  checking if key is expired")
	if key.IsExpired(time.Now().Unix()) {
		return nil, fmt.Errorf("ox: private key is expired: %s", key.GetFingerprint())
	}
	return key, nil
}

func oxStoreKey(location string, key string) error {
	var file *os.File
	slog.Info("ox: storing key:", "location", location)
	file, err := os.Create(location)
	if err != nil {
		return fmt.Errorf("ox: store key: failed to create key location: %w", err)
	}
	if runtime.GOOS != "windows" {
		_ = file.Chmod(os.FileMode(defaultFileRights))
	} else {
		_ = file.Chmod(os.FileMode(defaultFileRightsWin))
	}
	slog.Info("ox: storing key: writing key to file")
	_, err = file.Write([]byte(key))
	if err != nil {
		return fmt.Errorf("ox: store key: failed to write key to file: %w", err)
	}
	err = file.Close()
	if err != nil {
		fmt.Println("error while closing file:", err)
	}
	return nil
}

func oxGenPrivKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ,
	passphrase string, keyType int,
) error {
	xmppURI := "xmpp:" + jid
	slog.Info("ox: generating privkey:", "jid", xmppURI, "keytype", keyType)
	pgp := crypto.PGP()
	privKey, err := pgp.KeyGeneration().
		AddUserId(xmppURI, "").
		OverrideProfileAlgorithm(keyType).
		New().GenerateKey()
	if err != nil {
		return fmt.Errorf("ox: generate privkey: failed to generate private key: %w", err)
	}
	key := privKey
	if passphrase != "" {
		slog.Info("ox: generating privkey: setting", "passphrase", "REDACTED")
		key, err = pgp.LockKey(privKey, []byte(passphrase))
		if err != nil {
			return fmt.Errorf("ox: generate privkey: failed to lock private key with passphrase: %w", err)
		}
	}
	slog.Info("ox: generating privkey: serializing key")
	keySerialized, err := key.Serialize()
	if err != nil {
		return fmt.Errorf("ox: generate privkey: failed to serialize private key: %w", err)
	}
	location, err := oxGetPrivKeyLoc(jid)
	if err != nil {
		return fmt.Errorf("ox: generate privkey: failed to get private key location: %w", err)
	}
	slog.Info("ox: generating privkey: storing base64 encoded key:", "location", location)
	err = oxStoreKey(location,
		base64.StdEncoding.EncodeToString(keySerialized))
	if err != nil {
		log.Fatal(err)
	}
	slog.Info("ox: generating privkey: deriving public key")
	decodedPubKey, err := key.GetPublicKey()
	if err != nil {
		return fmt.Errorf("ox: generate privkey: failed to decode public key: %w", err)
	}
	pubKey, err := crypto.NewKey(decodedPubKey)
	if err != nil {
		return fmt.Errorf("ox: generate privkey: failed to decode public key: %w", err)
	}
	err = oxPublishPubKey(jid, client, iqc, pubKey)
	if err != nil {
		return fmt.Errorf("ox: generate privkey: failed to publish public key: %w", err)
	}
	return nil
}

func oxRecvPublicKeys(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, fingerprint string) (*crypto.KeyRing, error) {
	opkr := etree.NewDocument()
	opkr.WriteSettings.AttrSingleQuote = true
	opkrPs := opkr.CreateElement("pubsub")
	opkrPs.CreateAttr("xmlns", nsPubsub)
	opkrPsItems := opkrPs.CreateElement("items")
	opkrPsItems.CreateAttr("node", nsOxPubKeys+":"+fingerprint)
	opkrPsItems.CreateAttr("max_items", "1")
	opkrString, err := opkr.WriteToString()
	if err != nil {
		return nil, fmt.Errorf("ox: receive public keys: failed to generate xml for public key request: %w", err)
	}
	slog.Info("ox: receiving public keys:", "recipient", recipient)
	oxPublicKey, err := sendIQ(client, iqc, recipient, "get", opkrString)
	if err != nil {
		return nil, fmt.Errorf("ox: receive public keys: iq error requesting public keys: %w", err)
	}
	if oxPublicKey.Type != strResult {
		return nil, fmt.Errorf("ox: error while requesting public key for %s",
			recipient)
	}
	oxPublicKeyXML := etree.NewDocument()
	err = oxPublicKeyXML.ReadFromBytes(oxPublicKey.Query)
	if err != nil {
		return nil, fmt.Errorf("ox: receive public keys: failed parsing iq reply to public key request: %w", err)
	}
	keyring, err := crypto.NewKeyRing(nil)
	if err != nil {
		return nil, fmt.Errorf("ox: receive public keys: failed reading public key: %w", err)
	}
	oxPublicKeyXMLPubsub := oxPublicKeyXML.SelectElement("pubsub")
	if oxPublicKeyXMLPubsub == nil {
		return nil, fmt.Errorf("ox: no pubsub element in reply to public key request")
	}
	oxPublicKeyXMLItems := oxPublicKeyXMLPubsub.SelectElement("items")
	if oxPublicKeyXMLItems == nil {
		return nil, fmt.Errorf("ox: no items element in reply to public key request")
	}
	oxPublicKeyXMLItem := oxPublicKeyXMLItems.SelectElement("item")
	if oxPublicKeyXMLItem == nil {
		return nil, fmt.Errorf("ox: no item element in reply to public key request")
	}
	slog.Info("ox: receiving public keys: received public keys")
	oxPublicKeyXMLPubkeys := oxPublicKeyXMLItem.SelectElements("pubkey")
	for _, r := range oxPublicKeyXMLPubkeys {
		slog.Info("ox: receiving public keys: decoding public", "key", r)
		data := r.SelectElement("data")
		if data == nil {
			continue
		}
		decodedPubKey, err := base64.StdEncoding.DecodeString(data.Text())
		if err != nil {
			return nil, fmt.Errorf("ox: receive public keys: failed to decode public key: %w", err)
		}
		key, err := crypto.NewKey(decodedPubKey)
		if err != nil {
			return nil, fmt.Errorf("ox: receive public keys: failed to decode public key: %w", err)
		}
		slog.Info("ox: receiving public keys: checking for expiry:", "fingerprint", fingerprint)
		if key.IsExpired(time.Now().Unix()) {
			return nil, fmt.Errorf("ox: key is expired: %s", fingerprint)
		}
		err = keyring.AddKey(key)
		if err != nil {
			return nil, fmt.Errorf("ox: receive public keys: failed adding public key to keyring: %w", err)
		}
	}
	return keyring, nil
}

func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string) (*crypto.KeyRing, error) {
	publicKeyRing, err := crypto.NewKeyRing(nil)
	if err != nil {
		return nil, fmt.Errorf("ox: get public keyring: failed to create a new keyring: %w", err)
	}

	oxPubKeyListReq := etree.NewDocument()
	oxPubKeyListReq.WriteSettings.AttrSingleQuote = true
	oxPubKeyListReqPs := oxPubKeyListReq.CreateElement("pubsub")
	oxPubKeyListReqPs.CreateAttr("xmlns", nsPubsub)
	oxPubKeyListReqPsItems := oxPubKeyListReqPs.CreateElement("items")
	oxPubKeyListReqPsItems.CreateAttr("node", nsOxPubKeys)
	oxPubKeyListReqPsItems.CreateAttr("max_items", "1")
	opkl, err := oxPubKeyListReq.WriteToString()
	if err != nil {
		log.Fatal(err)
	}
	oxPublicKeyList, err := sendIQ(client, iqc, recipient, "get", opkl)
	if err != nil {
		log.Fatal(err)
	}
	if oxPublicKeyList.Type != strResult {
		return nil, fmt.Errorf("ox: error while requesting public openpgp keys for %s",
			recipient)
	}
	oxPubKeyListXML := etree.NewDocument()
	err = oxPubKeyListXML.ReadFromBytes(oxPublicKeyList.Query)
	if err != nil {
		return nil, fmt.Errorf("ox: get public keyring: failed to parse answer to public key list request: %w", err)
	}

	pubKeyRingID := "none"
	newestKey, err := time.Parse(time.RFC3339, "1900-01-01T00:00:00Z")
	if err != nil {
		return nil, fmt.Errorf("ox: get public keyring: failed to set time for newest key to 1900-01-01: %w", err)
	}

	oxPubKeyListXMLPubsub := oxPubKeyListXML.SelectElement("pubsub")
	if oxPubKeyListXMLPubsub == nil {
		return nil, fmt.Errorf("ox: no pubsub element in public key list")
	}
	oxPubKeyListXMLPubsubItems := oxPubKeyListXMLPubsub.SelectElement("items")
	if oxPubKeyListXMLPubsubItems == nil {
		return nil, fmt.Errorf("ox: no items element in public key list")
	}
	oxPubKeyListXMLPubsubItemsItem := oxPubKeyListXMLPubsubItems.SelectElement("item")
	if oxPubKeyListXMLPubsubItemsItem == nil {
		return nil, fmt.Errorf("ox: no item element in public key list")
	}
	oxPubKeyListXMLPubsubItemsItemPkl := oxPubKeyListXMLPubsubItemsItem.SelectElement("public-keys-list")
	if oxPubKeyListXMLPubsubItemsItemPkl == nil {
		return nil, fmt.Errorf("ox: no public-keys-list element")
	}
	oxPubKeyListXMLPubsubItemsItemPklPm := oxPubKeyListXMLPubsubItemsItemPkl.SelectElements("pubkey-metadata")
	for _, r := range oxPubKeyListXMLPubsubItemsItemPklPm {
		date := r.SelectAttr("date")
		if date == nil {
			continue
		}
		fingerprint := r.SelectAttr("v4-fingerprint")
		if fingerprint == nil {
			continue
		}
		keyDate, err := time.Parse(time.RFC3339, date.Value)
		if err != nil {
			return nil, fmt.Errorf("ox: get public keyring: failed to parse time stamp for key: %w", err)
		}
		if keyDate.After(newestKey) {
			newestKey = keyDate
			pubKeyRingID = fingerprint.Value
		}
	}
	if pubKeyRingID == "none" {
		return nil, fmt.Errorf("ox: server didn't provide public key fingerprints for %s", recipient)
	}

	pubKeyRingLocation, err := oxGetPubKeyLoc(pubKeyRingID)
	if err != nil {
		return nil, fmt.Errorf("ox: get public keyring: failed to get public key ring location: %w", err)
	}

	pubKeyReadXML := etree.NewDocument()
	err = pubKeyReadXML.ReadFromFile(pubKeyRingLocation)
	if err == nil {
		date := pubKeyReadXML.SelectElement("date")
		if date != nil {
			savedKeysDate, err := time.Parse(time.RFC3339, date.Text())
			if err != nil {
				return nil, fmt.Errorf("ox: get public keyring: failed to parse time for saved key: %w", err)
			}
			if !savedKeysDate.Before(newestKey) {
				pubKeys := pubKeyReadXML.SelectElements("pubkey")
				if pubKeys == nil {
					return nil, fmt.Errorf("ox: couldn't read public keys from cache")
				}
				for _, r := range pubKeys {
					keyByte, err := base64.StdEncoding.DecodeString(r.Text())
					if err != nil {
						return nil, fmt.Errorf("ox: get public keyring: failed to decode saved key: %w", err)
					}
					key, err := crypto.NewKey(keyByte)
					if err != nil {
						return nil, fmt.Errorf("ox: get public keyring: failed to parse saved key: %w", err)
					}
					if !key.IsExpired(time.Now().Unix()) {
						err = publicKeyRing.AddKey(key)
						if err != nil {
							return nil, fmt.Errorf("ox: get public keyring: failed to add key to public keyring: %w", err)
						}
					}
				}
				if publicKeyRing.CanEncrypt(time.Now().Unix()) {
					return publicKeyRing, nil
				}
			}
		}
	}
	pubKeyRing, err := oxRecvPublicKeys(client, iqc, recipient, pubKeyRingID)
	if err != nil {
		return nil, fmt.Errorf("ox: get public keyring: failed to get public keyring: %w", err)
	}
	pubKeySaveXML := etree.NewDocument()
	date := pubKeySaveXML.CreateElement("date")
	date.SetText(newestKey.Format(time.RFC3339))
	for _, key := range pubKeyRing.GetKeys() {
		keySerialized, err := key.Serialize()
		if err != nil {
			return nil, fmt.Errorf("ox: get public keyring: failed to serialize key: %w", err)
		}
		saveKey := pubKeySaveXML.CreateElement("pubkey")
		saveKey.SetText(base64.StdEncoding.EncodeToString(keySerialized))
	}
	err = pubKeySaveXML.WriteToFile(pubKeyRingLocation)
	if err != nil {
		return nil, fmt.Errorf("ox: get public keyring: failed to create xml for saving public key: %w", err)
	}
	return pubKeyRing, nil
}

func oxEncrypt(client *xmpp.Client, oxPrivKey *crypto.Key, recipient string, keyRing crypto.KeyRing, message string, subject string) (string, error) {
	if message == "" {
		return "", nil
	}
	ownJid := strings.Split(client.JID(), "/")[0]
	if recipient != ownJid {
		opk, err := oxPrivKey.GetPublicKey()
		if err == nil {
			ownKey, _ := crypto.NewKey(opk)
			_ = keyRing.AddKey(ownKey)
		}
	}
	oxCryptMessage := etree.NewDocument()
	oxCryptMessage.WriteSettings.AttrSingleQuote = true
	oxCryptMessageSc := oxCryptMessage.CreateElement("signcrypt")
	oxCryptMessageSc.CreateAttr("xmlns", nsOx)
	oxCryptMessageScTo := oxCryptMessageSc.CreateElement("to")
	oxCryptMessageScTo.CreateAttr("jid", recipient)
	oxCryptMessageScTime := oxCryptMessageSc.CreateElement("time")
	oxCryptMessageScTime.CreateAttr("stamp", time.Now().UTC().Format("2006-01-02T15:04:05Z"))
	oxCryptMessageScRpad := oxCryptMessageSc.CreateElement("rpad")
	oxCryptMessageScRpad.CreateText(getRpad(len(message)))
	oxCryptMessageScPayload := oxCryptMessageSc.CreateElement("payload")
	if subject != "" {
		oxCryptMessageScPayloadSub := oxCryptMessageScPayload.CreateElement("subject")
		oxCryptMessageScPayloadSub.CreateText(subject)
	}
	oxCryptMessageScPayloadBody := oxCryptMessageScPayload.CreateElement("body")
	oxCryptMessageScPayloadBody.CreateAttr("xmlns", nsJabberClient)
	oxCryptMessageScPayloadBody.CreateText(message)
	ocm, err := oxCryptMessage.WriteToString()
	if err != nil {
		return strError, fmt.Errorf("ox: encrypt: failed to create xml for ox crypt message: %w", err)
	}
	pgpEncrypt, err := crypto.PGP().Encryption().
		Recipients(&keyRing).
		SigningKey(oxPrivKey).New()
	if err != nil {
		return strError, fmt.Errorf("oxEncrypt: failed to create pgp encryption interface: %w", err)
	}
	pgpMessage, err := pgpEncrypt.Encrypt([]byte(ocm))
	if err != nil {
		return strError, fmt.Errorf("ox: encrypt: failed to create pgp message: %w", err)
	}
	om := etree.NewDocument()
	om.WriteSettings.AttrSingleQuote = true
	omMessage := om.CreateElement("message")
	omMessage.CreateAttr("to", recipient)
	omMessage.CreateAttr("id", getID())
	omMessageStore := omMessage.CreateElement("store")
	omMessageStore.CreateAttr("xmlns", nsHints)
	omMessageEme := omMessage.CreateElement("encryption")
	omMessageEme.CreateAttr("xmlns", nsEme)
	omMessageEme.CreateAttr("namespace", nsOx)
	omMessageOpgp := omMessage.CreateElement("openpgp")
	omMessageOpgp.CreateAttr("xmlns", nsOx)
	omMessageOpgp.CreateText(base64.StdEncoding.EncodeToString(pgpMessage.Bytes()))
	omMessageBody := omMessage.CreateElement("body")
	omMessageBody.CreateText(oxAltBody)
	oms, err := om.WriteToString()
	if err != nil {
		return strError, fmt.Errorf("ox: encrypt: failed to create xml for ox message: %w", err)
	}

	return oms, nil
}