-
Notifications
You must be signed in to change notification settings - Fork 6
/
otr.cpp
1329 lines (1179 loc) · 48.4 KB
/
otr.cpp
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2004-2013 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/Chan.h>
#include <znc/Client.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <znc/Threads.h>
#include <znc/User.h>
#include <znc/Utils.h>
extern "C" {
#include <libotr/proto.h>
#include <libotr/instag.h>
#include <libotr/message.h>
#include <libotr/privkey.h>
#include <libotr/userstate.h>
#include <libotr/version.h>
}
// See http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#include <cassert>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <regex>
using std::list;
using std::map;
#define PROTOCOL_ID "irc"
class COtrGenKeyJob : public CModuleJob {
public:
COtrGenKeyJob(CModule* pModule)
: CModuleJob(pModule, "OtrGenKey", "OTR key generator") {}
void runThread() override;
void runMain() override;
};
class COtrTimer : public CTimer {
public:
COtrTimer(CModule* pModule, unsigned int uInterval)
: CTimer(pModule, uInterval, /*run forever*/ 0, "OtrTimer",
"OTR message poll") {}
protected:
void RunJob() override;
};
struct COtrAppData {
bool bSmpReply = false;
static void Add(void* data, ConnContext* context) {
context->app_data = new COtrAppData();
context->app_data_free = Free;
}
static void Free(void* appdata) {
delete static_cast<COtrAppData*>(appdata);
}
};
class COtrMod : public CModule {
friend class COtrTimer;
friend class COtrGenKeyJob;
private:
static const OtrlMessageAppOps m_xOtrOps;
OtrlUserState m_pUserState;
CString m_sPrivkeyPath;
CString m_sFPPath;
CString m_sInsTagPath;
list<CString> m_Buffer;
VCString m_vsEnabled;
VCString m_vsIgnored;
COtrTimer* m_pOtrTimer;
// per-sender buffer of received partial OTR messages
map<CString, CString> m_MessageBuffer;
// m_GenKeyRunning acts as a lock for members following it. We don't need
// an actual lock because it is accessed only from the main thread.
bool m_GenKeyRunning;
void* m_NewKey;
gcry_error_t m_GenKeyError;
public:
MODCONSTRUCTOR(COtrMod) {}
bool PutModuleBuffered(const CString& sLine) {
CUser* user = GetUser();
bool attached = user->IsUserAttached();
if (attached) {
PutModule(sLine);
} else {
m_Buffer.push_back(sLine);
}
return attached;
}
bool PutModuleContext(ConnContext* ctx, const CString& sLine) {
assert(ctx);
assert(ctx->username);
return PutModuleBuffered(CString("[") + ctx->username + "] " + sLine);
}
enum Color { Blue = 2, Green = 3, Red = 4, Bold = 32 };
static CString Clr(Color eClr, const CString& sWhat) {
if (eClr == Bold) {
return CString("\x02") + sWhat + "\x02";
} else {
return CString("\x03") + (char)eClr + sWhat + "\x03";
}
}
static CString HumanFingerprint(Fingerprint* fprint) {
char human[OTRL_PRIVKEY_FPRINT_HUMAN_LEN];
otrl_privkey_hash_to_human(human, fprint->fingerprint);
return human;
}
CString OurFingerprint() {
char ourfp[OTRL_PRIVKEY_FPRINT_HUMAN_LEN];
CString accountname = GetUser()->GetUserName();
if (otrl_privkey_fingerprint(m_pUserState, ourfp, accountname.c_str(),
PROTOCOL_ID)) {
return ourfp;
}
return "ERROR";
}
void WriteFingerprints() {
gcry_error_t err = otrl_privkey_write_fingerprints(m_pUserState,
m_sFPPath.c_str());
if (err) {
PutModuleBuffered(CString("Failed to write fingerprints: ") +
gcry_strerror(err));
}
}
void WarnIfLoggingEnabled() {
assert(GetNetwork());
bool bUserMod = GetUser()->GetModules().FindModule("log");
bool bNetworkMod = GetNetwork()->GetModules().FindModule("log");
if (bUserMod || bNetworkMod) {
CString sMsg =
Clr(Red, "WARNING:") + " The log module is loaded. Type ";
if (bUserMod) {
sMsg += Clr(Bold, "/msg *status UnloadMod log") + " ";
if (bNetworkMod) {
sMsg += "and ";
}
}
if (bNetworkMod) {
sMsg += Clr(Bold, "/msg *status UnloadMod --type=network log") +
" ";
}
sMsg += "to prevent ZNC from logging the conversation to disk.";
PutModuleBuffered(sMsg);
}
}
void CmdInfo(const CString& sLine) {
CTable table;
table.AddColumn("Peer");
table.AddColumn("State");
table.AddColumn("Fingerprint");
table.AddColumn("Act");
table.AddColumn("Trust");
ConnContext* ctx;
for (ctx = m_pUserState->context_root; ctx; ctx = ctx->next) {
// Iterate over master contexts since only they have the fingerprint
// list.
if (ctx->m_context != ctx) continue;
// Show the state for the OTRL_INSTAG_BEST context, since that's the
// one we
// send our messages to.
assert(ctx->username);
ConnContext* best_ctx = otrl_context_find(
m_pUserState, ctx->username, GetUser()->GetUserName().c_str(),
PROTOCOL_ID, OTRL_INSTAG_BEST, 0, nullptr, nullptr, nullptr);
if (!best_ctx) continue;
CString state;
switch (best_ctx->msgstate) {
case OTRL_MSGSTATE_PLAINTEXT:
state = "plaintext";
break;
case OTRL_MSGSTATE_ENCRYPTED:
state = "encrypted";
break;
case OTRL_MSGSTATE_FINISHED:
state = "finished";
break;
default:
state = "unknown";
break;
}
Fingerprint* fp;
for (fp = ctx->fingerprint_root.next; fp; fp = fp->next) {
const char* trust;
if (!fp->trust || fp->trust[0] == '\0') {
trust = "not trusted";
} else if (0 == strcmp(fp->trust, "smp")) {
trust = "shared secret";
} else {
trust = fp->trust;
}
table.AddRow();
if (fp == ctx->fingerprint_root.next) {
table.SetCell("Peer", ctx->username);
table.SetCell("State", state);
}
table.SetCell("Fingerprint", HumanFingerprint(fp));
table.SetCell("Trust", trust);
if (fp == best_ctx->active_fingerprint) {
table.SetCell("Act", " * ");
}
}
}
if (m_pUserState->context_root) {
PutModule(table);
} else {
PutModule("No fingerprints available.");
}
PutModule("Your fingerprint: " + OurFingerprint() + ".");
}
ConnContext* GetContextFromArg(const CString& sLine,
bool bWarnIfNotFound = true) {
CString sNick = sLine.Token(1).MakeLower();
ConnContext* ctx = otrl_context_find(
m_pUserState, sNick.c_str(), GetUser()->GetUserName().c_str(),
PROTOCOL_ID, OTRL_INSTAG_BEST, 0, NULL, NULL, NULL);
if (!ctx && bWarnIfNotFound) {
PutModuleBuffered("Context for nick '" + sNick + "' not found.");
}
return ctx;
}
bool GetFprintFromArg(const CString& sLine, ConnContext*& ctx,
Fingerprint*& fprint) {
fprint = NULL;
// Try interpreting the argument as a nick and if we don't find a
// context, interpret
// it as human readable form of fingerprint.
ctx = GetContextFromArg(sLine, false);
if (ctx) {
fprint = ctx->active_fingerprint;
if (!fprint) {
PutModuleContext(ctx, "No active fingerprint.");
return false;
}
} else {
CString sNormalizedFP = sLine.Token(1, true).Replace_n(" ", "");
for (ConnContext* curctx = m_pUserState->context_root; curctx;
curctx = curctx->next) {
for (Fingerprint* curfp = curctx->fingerprint_root.next; curfp;
curfp = curfp->next) {
CString sCtxFP = HumanFingerprint(curfp).Replace_n(" ", "");
if (sCtxFP.Equals(sNormalizedFP, false)) {
fprint = curfp;
ctx = curctx;
}
}
}
}
if (!fprint) {
PutModuleBuffered(
"Fingerprint not found. This comand takes either nick "
"or hexadecimal fingerprint as an argument.");
return false;
}
return true;
}
void CmdTrust(const CString& sLine) {
ConnContext* ctx;
Fingerprint* fprint;
if (!GetFprintFromArg(sLine, ctx, fprint)) {
return;
}
int already_trusted = otrl_context_is_fingerprint_trusted(fprint);
if (already_trusted) {
PutModuleContext(ctx, CString("Fingerprint ") +
HumanFingerprint(fprint) +
" already trusted.");
} else {
otrl_context_set_trust(fprint, "manual");
PutModuleContext(ctx, CString("Fingerprint ") +
HumanFingerprint(fprint) + " trusted!");
WriteFingerprints();
}
}
void CmdDistrust(const CString& sLine) {
ConnContext* ctx;
Fingerprint* fprint;
if (!GetFprintFromArg(sLine, ctx, fprint)) {
return;
}
int trusted = otrl_context_is_fingerprint_trusted(fprint);
if (!trusted) {
PutModuleContext(ctx, CString("Already not trusting ") +
HumanFingerprint(fprint) + ".");
} else {
otrl_context_set_trust(fprint, "");
PutModuleContext(ctx, CString("Fingerprint ") +
HumanFingerprint(fprint) +
" distrusted!");
WriteFingerprints();
}
}
void CmdFinish(const CString& sLine) {
ConnContext* ctx = GetContextFromArg(sLine);
if (!ctx) {
return;
}
otrl_message_disconnect(m_pUserState, &m_xOtrOps, this,
ctx->accountname, PROTOCOL_ID, ctx->username,
ctx->their_instance);
PutModuleContext(ctx, "Conversation finished.");
}
void DoSMP(ConnContext* ctx, const CString& sQuestion,
const CString& sSecret) {
if (sSecret.empty()) {
PutModuleContext(ctx, "No secret given!");
return;
}
if (ctx->msgstate != OTRL_MSGSTATE_ENCRYPTED) {
PutModuleContext(ctx, "Not in OTR session.");
return;
}
COtrAppData* ad = static_cast<COtrAppData*>(ctx->app_data);
assert(ad);
if (ad->bSmpReply) {
otrl_message_respond_smp(
m_pUserState, &m_xOtrOps, this, ctx,
reinterpret_cast<const unsigned char*>(sSecret.c_str()),
sSecret.length());
PutModuleContext(ctx, "Responded to authentication.");
} else {
if (sQuestion.empty()) {
otrl_message_initiate_smp(
m_pUserState, &m_xOtrOps, this, ctx,
reinterpret_cast<const unsigned char*>(sSecret.c_str()),
sSecret.length());
} else {
otrl_message_initiate_smp_q(
m_pUserState, &m_xOtrOps, this, ctx, sQuestion.c_str(),
reinterpret_cast<const unsigned char*>(sSecret.c_str()),
sSecret.length());
}
PutModuleContext(ctx, "Initiated authentication.");
}
ad->bSmpReply = false;
}
void CmdAuth(const CString& sLine) {
ConnContext* ctx = GetContextFromArg(sLine);
if (!ctx) {
return;
}
CString sSecret = sLine.Token(2, true);
DoSMP(ctx, "", sSecret);
}
void CmdAuthQ(const CString& sLine) {
ConnContext* ctx = GetContextFromArg(sLine);
if (!ctx) {
return;
}
COtrAppData* ad = static_cast<COtrAppData*>(ctx->app_data);
assert(ad);
if (ad->bSmpReply) {
PutModuleContext(ctx,
"Authentication in progress. Use Auth to "
"respond with secret, or AuthAbort to abort it");
return;
}
CString sRest = sLine.Token(2, true);
if (sRest.length() == 0 || sRest[0] != '[') {
PutModuleContext(ctx,
"No question found. Did you enclose it in "
"square brackets?");
return;
}
size_t iQEnd = sRest.find(']', 1);
if (iQEnd == CString::npos) {
PutModuleContext(ctx, "Closing bracket missing for question.");
return;
}
if (iQEnd + 1 == sRest.length()) {
PutModuleContext(ctx, "No secret given!");
return;
}
CString sQuestion = sRest.substr(1, iQEnd - 1);
CString sSecret = sRest.substr(iQEnd + 1, CString::npos);
sSecret.Trim();
DoSMP(ctx, sQuestion, sSecret);
}
void CmdAuthAbort(const CString& sLine) {
ConnContext* ctx = GetContextFromArg(sLine);
if (!ctx) {
return;
}
COtrAppData* ad = static_cast<COtrAppData*>(ctx->app_data);
assert(ad);
ad->bSmpReply = false;
otrl_message_abort_smp(m_pUserState, &m_xOtrOps, this, ctx);
PutModuleContext(ctx, "Authentication aborted.");
}
void CmdGenKey(const CString& sLine) {
assert(m_pUserState);
const char* accountname = GetUser()->GetUserName().c_str();
bool bHasKey =
otrl_privkey_find(m_pUserState, accountname, PROTOCOL_ID);
bool bOverwrite = sLine.Token(1).Equals("--overwrite");
bool bReally = sLine.Token(1).Equals("--really");
if (bHasKey && !bOverwrite) {
PutModuleBuffered("Private key already exists. Use " +
Clr(Bold, "genkey --overwrite") +
" to overwrite the old one.");
return;
}
if (!bHasKey && !bReally) {
PutModuleBuffered(Clr(Red, "WARNING:") +
" This plugin does not provide true end-to-end "
"encryption, as the encryption terminates at "
"the bouncer. You need to make sure that both "
"the bouncer and your client's connection to "
"it are secure.");
PutModuleBuffered(Clr(Bold, "NOTE:") +
" If you're running this plugin on a VM, make "
"sure it has sufficient entropy, otherwise ZNC "
"might get stuck. Install haveged to increase "
"available entropy.");
PutModuleBuffered(
"If you still want to generate new OTR key, type " +
Clr(Bold, "genkey --really") + ".");
return;
}
if (m_GenKeyRunning) {
PutModuleBuffered("Key generation is already running.");
return;
}
gcry_error_t err = otrl_privkey_generate_start(
m_pUserState, accountname, PROTOCOL_ID, &m_NewKey);
if (err) {
PutModuleBuffered(CString("Key generation failed: ") +
gcry_strerror(err));
return;
}
PutModuleBuffered("Starting key generation in a background thread.");
m_GenKeyRunning = true;
AddJob(new COtrGenKeyJob(this));
}
void SaveIgnores() {
CString sFlat = CString(" ").Join(m_vsIgnored.begin(), m_vsIgnored.end());
SetNV("ignore", sFlat, true);
if (m_vsEnabled.empty()) {
// A single space to avoid the default getting restored
sFlat = CString(" ");
} else {
sFlat = CString(" ").Join(m_vsEnabled.begin(), m_vsEnabled.end());
}
SetNV("enable", sFlat, true);
}
bool IsIgnored(const CString& sNick) {
CString sNickLower = sNick.AsLower();
bool bEnabled = false;
for (const CString& s : m_vsEnabled) {
if (sNickLower.WildCmp(s)) {
bEnabled = true;
break;
}
}
if (!bEnabled) {
return true;
}
for (const CString& s : m_vsIgnored) {
if (sNickLower.WildCmp(s)) {
return true;
}
}
return false;
}
void CmdIgnore(const CString& sLine) {
CString sEnDis;
VCString *pList;
if (sLine.Token(0) == "ignore") {
sEnDis = "disabled";
pList = &m_vsIgnored;
} else {
sEnDis = "enabled";
pList = &m_vsEnabled;
}
if (sLine.Token(1).empty()) {
PutModuleBuffered(CString("OTR is ") + sEnDis + " for following nicks:");
for (const CString& s : *pList) {
PutModuleBuffered(s);
}
} else if (sLine.Token(1).Equals("--remove")) {
CString sNick = sLine.Token(2);
if (sNick.empty()) {
PutModuleBuffered("Usage: " + sLine.Token(0) + " --remove nick");
return;
}
bool bFound = false;
for (VCString::iterator it = pList->begin(); //range-based for
it != pList->end(); it++) {
if (it->Equals(sNick)) {
pList->erase(it);
bFound = true;
break;
}
}
if (bFound) {
SaveIgnores();
PutModuleBuffered("Removed " + Clr(Bold, sNick) +
" from OTR " + sLine.Token(0) + " list.");
} else {
PutModuleBuffered("Not on OTR " + sLine.Token(0) + " list: " + sNick);
}
} else {
CString sNick = sLine.Token(1).MakeLower();
pList->push_back(sNick);
SaveIgnores();
PutModuleBuffered("Added " + Clr(Bold, sNick) +
" to OTR " + sLine.Token(0) + " list.");
}
}
bool OnLoad(const CString& sArgs, CString& sMessage) override {
// Initialize libgcrypt for multithreaded usage
gcry_error_t err = gcry_control(GCRYCTL_SET_THREAD_CBS,
&gcry_threads_pthread);
if (err) {
sMessage = (CString("Failed to initialize gcrypt threading: ") +
gcry_strerror(err));
return false;
}
// Initialize libotr if needed
static bool otrInitialized = false;
if (!otrInitialized) {
OTRL_INIT;
otrInitialized = true;
}
// Initialize userstate
m_pUserState = otrl_userstate_create();
m_GenKeyRunning = false;
m_pOtrTimer = NULL;
m_sPrivkeyPath = GetSavePath() + "/otr.key";
m_sFPPath = GetSavePath() + "/otr.fp";
m_sInsTagPath = GetSavePath() + "/otr.instag";
// Load private key
err = otrl_privkey_read(m_pUserState, m_sPrivkeyPath.c_str());
if (gcry_err_code(err) == GPG_ERR_NO_ERROR) {
// PutModuleBuffered("Private keys loaded from " + m_sPrivkeyPath +
// ".");
} else if (gcry_err_code(err) == gcry_err_code_from_errno(ENOENT)) {
PutModuleBuffered("No private key found. Type " +
Clr(Bold, "genkey") + " to generate new one.");
} else {
sMessage = (CString("Failed to load private key: ") +
gcry_strerror(err) + ".");
return false;
}
// Load fingerprints
err = otrl_privkey_read_fingerprints(m_pUserState, m_sFPPath.c_str(),
COtrAppData::Add, NULL);
if (gcry_err_code(err) == GPG_ERR_NO_ERROR) {
// PutModuleBuffered("Fingerprints loaded from " + m_sFPPath + ".");
} else if (gcry_err_code(err) == gcry_err_code_from_errno(ENOENT)) {
// PutModuleBuffered("No fingerprint file found.");
} else {
sMessage = (CString("Failed to load fingerprints: ") +
gcry_strerror(err) + ".");
return false;
}
// Load instance tags
err = otrl_instag_read(m_pUserState, m_sInsTagPath.c_str());
if (gcry_err_code(err) == GPG_ERR_NO_ERROR) {
// PutModuleBuffered("Instance tags loaded from " + m_sInsTagPath +
// ".");
} else if (gcry_err_code(err) == gcry_err_code_from_errno(ENOENT)) {
// PutModuleBuffered("No instance tag file found.");
} else {
sMessage = (CString("Failed to load instance tags: ") +
gcry_strerror(err) + ".");
return false;
}
// Initialize commands
AddHelpCommand();
AddCommand("Info",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdInfo), "",
"List known fingerprints");
AddCommand(
"Trust", static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdTrust),
"<nick|fingerprint>",
"Mark the user's fingerprint as trusted after veryfing it over "
"secure channel.");
AddCommand("Distrust",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdDistrust),
"<nick|fingerprint>",
"Mark user's fingerprint as not trusted.");
AddCommand("Finish",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdFinish),
"<nick>", "Terminate an OTR conversation.");
AddCommand("Auth",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdAuth),
"<nick> <secret>", "Authenticate using shared secret.");
AddCommand("AuthQ",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdAuthQ),
"<nick> <[question]> <secret>",
"Authenticate using shared secret (providing a question).");
AddCommand("AuthAbort",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdAuthAbort),
"<nick>", "Abort authentication with peer.");
AddCommand("Enable",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdIgnore),
"[--remove] [nick]",
"Manage list of nicks enabled for OTR encryption. "
"Accepts wildcards.");
AddCommand("Ignore",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdIgnore),
"[--remove] [nick]",
"Manage list of nicks excluded from OTR encryption. "
"Accepts wildcards.");
AddCommand("GenKey",
static_cast<CModCommand::ModCmdFunc>(&COtrMod::CmdGenKey),
"[--really|--overwrite]", "Generate new private key.");
// Load list of ignored nicks
CString enabled_nicks = GetNV("enable");
if (enabled_nicks.empty()) {
// Default to enabled for all nicks
enabled_nicks = "*";
}
enabled_nicks.Split(" ", m_vsEnabled, false);
GetNV("ignore").Split(" ", m_vsIgnored, false);
// Warn if we are not an administrator - we should check if we are the
// only administrator. However, the user map may not be fully populated
// at this time.
if (!GetUser()->IsAdmin()) {
PutModuleBuffered(
Clr(Red, "WARNING:") +
" You are not a ZNC admin. "
"The ZNC administrator has access to your private keys "
"which can be used to read your encrypted messages and to "
"impersonate you.");
PutModuleBuffered(
"Do you trust their good intentions and the ability to "
"protect your data from other people?");
}
return true;
}
~COtrMod() override {
// No need to deactivate timers, they are removed in
// CModule::~CModule().
if (m_pUserState) otrl_userstate_free(m_pUserState);
}
static CString FindOtrQuery(const CString& sMessage) {
// Extract OTR query (e.g. ?OTR? or ?OTRv23?) from a message.
static const std::regex query{R"(\?OTR(\??v[a-z\d]*)?\?)"};
std::smatch m;
return std::regex_search(sMessage, m, query) ? m.str() : "";
}
static void DefaultQueryWorkaround(CString& sMessage) {
/* libotr replaces ?OTR? request by a string that contains html tags and
* newlines. The newlines confuse IRC server, and if we sent them in a
* separate PRIVMSG then they would show up regardless of other side's
* otr plugin presnece, defeating the purpose of the message. We replace
* that message here, keeping the OTR query.
*/
const CString& query = FindOtrQuery(sMessage);
if (!query.empty()) {
sMessage = query +
" Requesting an off-the-record private conversation."
" However, you do not have a plugin to support that."
" See https://otr.cypherpunks.ca/ for more information.";
}
}
bool TargetIsChan(const CString& sTarget) {
CIRCNetwork* network = GetNetwork();
assert(network);
if (sTarget.empty()) {
return true;
} else if (network->GetChanPrefixes().empty()) {
// RFC 2811
return (CString("&#!+").find(sTarget[0]) != CString::npos);
} else {
return (network->GetChanPrefixes().find(sTarget[0]) !=
CString::npos);
}
}
EModRet SendEncrypted(CString& sTarget, CString& sMessage) {
gcry_error_t err;
char* newmessage = NULL;
const char* accountname = GetUser()->GetUserName().c_str();
CString sNick = sTarget.AsLower();
err = otrl_message_sending(
m_pUserState, &m_xOtrOps, this, accountname, PROTOCOL_ID,
sNick.c_str(), OTRL_INSTAG_BEST, sMessage.c_str(), NULL,
&newmessage, OTRL_FRAGMENT_SEND_ALL, NULL, COtrAppData::Add, NULL);
if (err) {
PutModuleBuffered(CString("otrl_message_sending failed: ") +
gcry_strerror(err));
return HALT;
}
if (newmessage) {
// libotr injected the message
otrl_message_free(newmessage);
return HALT;
} else {
// not an OTR message
return CONTINUE;
}
}
EModRet OnUserMsg(CString& sTarget, CString& sMessage) override {
// Do not pass the message to libotr if sTarget is a channel
if (TargetIsChan(sTarget) || IsIgnored(sTarget)) {
return CONTINUE;
}
return SendEncrypted(sTarget, sMessage);
}
EModRet OnUserAction(CString& sTarget, CString& sMessage) override {
if (TargetIsChan(sTarget) || IsIgnored(sTarget)) {
return CONTINUE;
}
// http://www.cypherpunks.ca/pipermail/otr-dev/2012-December/001520.html
// suggests using following:
// CString sLine = "\001ACTION " + sMessage + "\001";
// However, irssi and weechat plugins send it like this:
CString sLine = "/me " + sMessage;
// Try sending the formatted line. If CONTINUE is returned,
// pass unformatted to other plugins/caller.
return SendEncrypted(sTarget, sLine);
}
static bool HasOtrMessageEnd(const CString& sMessage) {
return sMessage.EndsWith(".") || sMessage.EndsWith(",");
}
EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override {
int res;
char* newmessage = NULL;
OtrlTLV* tlvs = NULL;
ConnContext* ctx = NULL;
CString sNick = Nick.GetNick().AsLower();
if (IsIgnored(Nick.GetNick())) {
return CONTINUE;
}
// When using an XMPP to IRC gateway such as bitlbee, a single OTR
// message can get broken into multiple parts due to IRC message length
// limit. Buffer such parts until a whole OTR message is received, and
// only then pass it to libotr.
if (sMessage.StartsWith("?OTR")) {
if (!HasOtrMessageEnd(sMessage) && FindOtrQuery(sMessage).empty()) {
// received beginning of an incomplete OTR message (not a query);
// buffer it (replacing any existing data) and wait for rest
m_MessageBuffer[sNick] = sMessage;
return HALT;
}
} else {
auto buffer = m_MessageBuffer.find(sNick);
if (buffer != m_MessageBuffer.end()) {
// received the next part of a buffered OTR message
if (!HasOtrMessageEnd(sMessage)) {
// OTR message still incomplete, add new data to buffer
buffer->second += sMessage;
return HALT;
} else {
// this part completes a buffered OTR message
sMessage = buffer->second + sMessage;
m_MessageBuffer.erase(buffer);
}
}
}
const char* accountname = GetUser()->GetUserName().c_str();
res = otrl_message_receiving(m_pUserState, &m_xOtrOps, this,
accountname, PROTOCOL_ID, sNick.c_str(),
sMessage.c_str(), &newmessage, &tlvs, &ctx,
COtrAppData::Add, NULL);
if (ctx && otrl_tlv_find(tlvs, OTRL_TLV_DISCONNECTED)) {
PutModuleContext(
ctx,
"Peer has finished the conversation. "
"Type " +
Clr(Bold, "finish " + Nick.GetNick()) +
" to enter plaintext mode, or send ?OTR? to start "
"new OTR session.");
}
if (tlvs) {
otrl_tlv_free(tlvs);
}
if (res == 1) {
// PutModule("Received internal OTR message");
return HALT;
} else if (res != 0) {
PutModuleBuffered(
CString("otrl_message_receiving: unknown return code ") +
CString(res));
return HALT;
} else if (newmessage == NULL) {
// PutModule("Received non-encrypted privmsg");
return CONTINUE;
} else {
// PutModule("Received encrypted privmsg");
sMessage = CString(newmessage);
otrl_message_free(newmessage);
// Handle /me as sent by irssi and weechat plugins
if (sMessage.TrimPrefix("/me ")) {
sMessage = "\001ACTION " + sMessage + "\001";
}
return CONTINUE;
}
}
void OnClientLogin() override {
for (list<CString>::iterator it = m_Buffer.begin();
it != m_Buffer.end(); it++) {
PutModule(*it);
}
m_Buffer.clear();
}
private:
// libotr callbacks
static OtrlPolicy otrPolicy(void* opdata, ConnContext* context) {
return OTRL_POLICY_DEFAULT;
}
static void otrCreatePrivkey(void* opdata, const char* accountname,
const char* protocol) {
COtrMod* mod = static_cast<COtrMod*>(opdata);
assert(mod);
assert(0 == strcmp(protocol, PROTOCOL_ID));
mod->PutModuleBuffered(
"Someone wants to start an OTR session but you don't have a "
"key available. Type " + mod->Clr(Bold, "genkey") +
" to generate new one.");
}
static int otrIsLoggedIn(void* opdata, const char* accountname,
const char* protocol, const char* recipient) {
// Assume always online, otrl_message_disconnect does nothing otherwise.
return 1;
}
static void otrInjectMessage(void* opdata, const char* accountname,
const char* protocol, const char* recipient,
const char* message) {
COtrMod* mod = static_cast<COtrMod*>(opdata);
assert(mod);
assert(0 == strcmp(protocol, PROTOCOL_ID));
// libotr-4.0.0 injects empty message when sending to recipient in
// finished state
if (!message[0]) {
return;
}
CString sMessage(message);
if (!mod->TargetIsChan(CString(recipient))) {
DefaultQueryWorkaround(sMessage);
}
mod->PutIRC(CString("PRIVMSG ") + recipient + " :" + sMessage);
}
static void otrWriteFingerprints(void* opdata) {
COtrMod* mod = static_cast<COtrMod*>(opdata);
assert(mod);
mod->WriteFingerprints();
}
static void otrGoneSecure(void* opdata, ConnContext* context) {
COtrMod* mod = static_cast<COtrMod*>(opdata);
assert(mod);
mod->PutModuleContext(
context, "Gone " + mod->Clr(Bold, "SECURE") +
". Please "
"make sure logging is turned off on your IRC client.");
mod->WarnIfLoggingEnabled();
assert(context->active_fingerprint);
if (!otrl_context_is_fingerprint_trusted(context->active_fingerprint)) {
mod->PutModuleContext(context,
"Peer is not authenticated. There are two "
"ways of verifying their identity:");
mod->PutModuleContext(
context,
"1. Agree on a common secret (do not type "
"it into the chat), then type " +
mod->Clr(Bold, CString("auth ") + context->username +
" <secret>") +
".");
mod->PutModuleContext(
context,
"2. Compare their fingerprint over a "
"secure channel, then type " +
mod->Clr(Bold, CString("trust ") + context->username) +
".");
mod->PutModuleContext(
context,
"Your fingerprint: " + mod->Clr(Bold, mod->OurFingerprint()));