summaryrefslogtreecommitdiffstats
path: root/scripts/cap_sasl.pl
blob: 7a0b742c989efd811438af872b4bbb2f401c3785 (plain)
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
use strict;
use Irssi;
use MIME::Base64;
use vars qw($VERSION %IRSSI);
use constant CHALLENGE_SIZE => 32;

$VERSION = "1.11";
%IRSSI = (
	authors => 'Michael Tharp (gxti), Jilles Tjoelker (jilles), Mantas Mikulėnas (grawity)',
	contact => 'grawity@gmail.com',
	name => 'cap_sasl.pl',
	description => 'Implements SASL authentication and enables CAP "multi-prefix"',
	license => 'GPLv2',
	url => 'http://ircv3.atheme.org/extensions/sasl-3.1',
);

my %sasl_auth = ();
my %mech = ();

sub irssi_abspath {
	my $f = shift;
	$f =~ s!^~/!$ENV{HOME}/!;
	if ($f !~ m!^/!) {
		$f = Irssi::get_irssi_dir()."/".$f;
	}
	return $f;
}

sub timeout;

sub server_connected {
	my $server = shift;
	if (uc $server->{chat_type} eq 'IRC') {
		$server->send_raw_now("CAP LS");
	}
}

sub event_cap {
	my ($server, $args, $nick, $address) = @_;
	my ($subcmd, $caps, $tosend, $sasl);

	$tosend = '';
	$sasl = $sasl_auth{$server->{tag}};
	if ($args =~ /^\S+ (\S+) :(.*)$/) {
		$subcmd = uc $1;
		$caps = ' '.$2.' ';
		if ($subcmd eq 'LS') {
			$tosend .= ' multi-prefix' if $caps =~ / multi-prefix /i;
			$tosend .= ' sasl' if $caps =~ / sasl /i && defined($sasl);
			$tosend =~ s/^ //;
			$server->print('', "CLICAP: supported by server:$caps");
			if (!$server->{connected}) {
				if ($tosend eq '') {
					$server->send_raw_now("CAP END");
				} else {
					$server->print('', "CLICAP: requesting: $tosend");
					$server->send_raw_now("CAP REQ :$tosend");
				}
			}
			Irssi::signal_stop();
		} elsif ($subcmd eq 'ACK') {
			$server->print('', "CLICAP: now enabled:$caps");
			if ($caps =~ / sasl /i) {
				$sasl->{buffer} = '';
				$sasl->{step} = 0;
				if ($mech{$sasl->{mech}}) {
					$server->send_raw_now("AUTHENTICATE " . $sasl->{mech});
					Irssi::timeout_add_once(7500, \&timeout, $server->{tag});
				} else {
					$server->print('', 'SASL: attempted to start unknown mechanism "' . $sasl->{mech} . '"');
				}
			}
			elsif (!$server->{connected}) {
				$server->send_raw_now("CAP END");
			}
			Irssi::signal_stop();
		} elsif ($subcmd eq 'NAK') {
			$server->print('', "CLICAP: refused:$caps");
			if (!$server->{connected}) {
				$server->send_raw_now("CAP END");
			}
			Irssi::signal_stop();
		} elsif ($subcmd eq 'LIST') {
			$server->print('', "CLICAP: currently enabled:$caps");
			Irssi::signal_stop();
		}
	}
}

sub event_authenticate {
	my ($server, $args, $nick, $address) = @_;
	my $sasl = $sasl_auth{$server->{tag}};
	return unless $sasl && $mech{$sasl->{mech}};

	$sasl->{buffer} .= $args;
	return if length($args) == 400;

	my $data = ($sasl->{buffer} eq '+') ? '' : decode_base64($sasl->{buffer});
	my $out = $mech{$sasl->{mech}}($sasl, $data);

	if (defined $out) {
		$out = ($out eq '') ? '+' : encode_base64($out, '');
		while (length $out >= 400) {
			my $subout = substr($out, 0, 400, '');
			$server->send_raw_now("AUTHENTICATE $subout");
		}
		if (length $out) {
			$server->send_raw_now("AUTHENTICATE $out");
		} else {
			# Last piece was exactly 400 bytes, we have to send
			# some padding to indicate we're done.
			$server->send_raw_now("AUTHENTICATE +");
		}
	} else {
		$server->send_raw_now("AUTHENTICATE *");
	}

	$sasl->{buffer} = "";
	Irssi::signal_stop();
}

sub event_saslend {
	my ($server, $args, $nick, $address) = @_;

	my $data = $args;
	$data =~ s/^\S+ :?//;
	# need this to see it, ?? -- jilles

	$server->print('', $data);
	if (!$server->{connected}) {
		$server->send_raw_now("CAP END");
	}
}

sub event_saslfail {
	my ($server, $args, $nick, $address) = @_;

	my $data = $args;
	$data =~ s/^\S+ :?//;

	if (Irssi::settings_get_bool('sasl_disconnect_on_fail')) {
		$server->print('', "$data - disconnecting from server", MSGLEVEL_CLIENTERROR);
		$server->disconnect();
	} else {
		$server->print('', "$data - continuing anyway");
		if (!$server->{connected}) {
			$server->send_raw_now("CAP END");
		}
	}
}

sub timeout {
	my $tag = shift;
	my $server = Irssi::server_find_tag($tag);
	if ($server && !$server->{connected}) {
		$server->print('', "SASL: authentication timed out", MSGLEVEL_CLIENTERROR);
		$server->send_raw_now("CAP END");
	}
}

sub cmd_sasl {
	my ($data, $server, $item) = @_;

	if ($data ne '') {
		Irssi::command_runsub ('sasl', $data, $server, $item);
	} else {
		cmd_sasl_show(@_);
	}
}

sub cmd_sasl_set {
	my ($data, $server, $item) = @_;

	if (my ($net, $u, $p, $m) = $data =~ /^(\S+) (\S+) (\S+) (\S+)$/) {
		if ($mech{uc $m}) {
			$sasl_auth{$net}{user} = $u;
			$sasl_auth{$net}{password} = $p;
			$sasl_auth{$net}{mech} = uc $m;
			Irssi::print("SASL: added $net: [$m] $sasl_auth{$net}{user} *");
		} else {
			Irssi::print("SASL: unknown mechanism $m", MSGLEVEL_CLIENTERROR);
		}
	} elsif ($data =~ /^(\S+)$/) {
		$net = $1;
		if (defined($sasl_auth{$net})) {
			delete $sasl_auth{$net};
			Irssi::print("SASL: deleted $net");
		} else {
			Irssi::print("SASL: no entry for $net");
		}
	} else {
		Irssi::print("SASL: usage: /sasl set <net> <user> <password or keyfile> <mechanism>");
	}
}

sub cmd_sasl_show {
	#my ($data, $server, $item) = @_;
	my @nets = keys %sasl_auth;
	for my $net (@nets) {
		Irssi::print("SASL: $net: [$sasl_auth{$net}{mech}] $sasl_auth{$net}{user} *");
	}
	Irssi::print("SASL: no networks defined") if !@nets;
}

sub cmd_sasl_save {
	#my ($data, $server, $item) = @_;
	my $file = Irssi::get_irssi_dir()."/sasl.auth";
	if (open(my $fh, ">", $file)) {
		chmod(0600, $file);
		for my $net (keys %sasl_auth) {
			printf $fh ("%s\t%s\t%s\t%s\n",
				$net,
				$sasl_auth{$net}{user},
				$sasl_auth{$net}{password},
				$sasl_auth{$net}{mech});
		}
		close($fh);
		Irssi::print("SASL: auth saved to '$file'");
	} else {
		Irssi::print("SASL: couldn't access '$file': $@");
	}
}

sub cmd_sasl_load {
	#my ($data, $server, $item) = @_;
	my $file = Irssi::get_irssi_dir()."/sasl.auth";
	if (open(my $fh, "<", $file)) {
		%sasl_auth = ();
		while (<$fh>) {
			chomp;
			my ($net, $u, $p, $m) = split(/\t/, $_, 4);
			$m ||= "PLAIN";
			if ($mech{uc $m}) {
				$sasl_auth{$net}{user} = $u;
				$sasl_auth{$net}{password} = $p;
				$sasl_auth{$net}{mech} = uc $m;
			} else {
				Irssi::print("SASL: unknown mechanism $m", MSGLEVEL_CLIENTERROR);
			}
		}
		close($fh);
		Irssi::print("SASL: cap_sasl $VERSION, auth loaded from '$file'");
	}
}

sub cmd_sasl_mechanisms {
	Irssi::print("SASL: mechanisms supported: " . join(", ", sort keys %mech));
}

Irssi::settings_add_bool('server', 'sasl_disconnect_on_fail', 1);

Irssi::signal_add_first('server connected', \&server_connected);
Irssi::signal_add('event cap', \&event_cap);
Irssi::signal_add('event authenticate', \&event_authenticate);
Irssi::signal_add('event 903', \&event_saslend);
Irssi::signal_add('event 904', \&event_saslfail);
Irssi::signal_add('event 905', \&event_saslend);
Irssi::signal_add('event 906', \&event_saslfail);
Irssi::signal_add('event 907', \&event_saslend);

Irssi::command_bind('sasl', \&cmd_sasl);
Irssi::command_bind('sasl load', \&cmd_sasl_load);
Irssi::command_bind('sasl save', \&cmd_sasl_save);
Irssi::command_bind('sasl set', \&cmd_sasl_set);
Irssi::command_bind('sasl show', \&cmd_sasl_show);
Irssi::command_bind('sasl mechanisms', \&cmd_sasl_mechanisms);

$mech{PLAIN} = sub {
	my ($sasl, $data) = @_;
	my $u = $sasl->{user};
	my $p = $sasl->{password};
	return join("\0", $u, $u, $p);
};

$mech{EXTERNAL} = sub {
	my ($sasl, $data) = @_;
	return $sasl->{user} // "";
};

if (eval {require Crypt::PK::ECC}) {
	my $mech = "ECDSA-NIST256P-CHALLENGE";

	$mech{'ECDSA-NIST256P-CHALLENGE'} = sub {
		my ($sasl, $data) = @_;
		my $u = $sasl->{user};
		my $f = $sasl->{password};
		$f = irssi_abspath($f);
		if (!-f $f) {
			Irssi::print("SASL: key file '$f' not found", MSGLEVEL_CLIENTERROR);
			return;
		}
		my $pk = eval {Crypt::PK::ECC->new($f)};
		if ($@ || !$pk || !$pk->is_private) {
			Irssi::print("SASL: no private key in file '$f'", MSGLEVEL_CLIENTERROR);
			return;
		}
		my $step = ++$sasl->{step};
		if ($step == 1) {
			if (length $data == CHALLENGE_SIZE) {
				my $sig = $pk->sign_hash($data);
				return $u."\0".$u."\0".$sig;
			} elsif (length $data) {
				return;
			} else {
				return $u."\0".$u;
			}
		}
		elsif ($step == 2) {
			if (length $data == CHALLENGE_SIZE) {
				return $pk->sign_hash($data);
			} else {
				return;
			}
		}
	};

	Irssi::command_bind("sasl keygen" => sub {
		my ($data, $server, $witem) = @_;

		my $print = $server
				? sub { $server->print("", shift, shift // MSGLEVEL_CLIENTNOTICE) }
				: sub { Irssi::print(shift, shift // MSGLEVEL_CLIENTNOTICE) };

		my $net = $server ? $server->{tag} : $data;
		if (!length $net) {
			Irssi::print("SASL: please connect to a server first",
						MSGLEVEL_CLIENTERROR);
			return;
		}

		my $f_name = lc "sasl-ecdsa-$net";
		   $f_name =~ s![ /]+!_!g;
		my $f_priv = Irssi::get_irssi_dir()."/$f_name.key";
		my $f_pub  = Irssi::get_irssi_dir()."/$f_name.pub";
		if (-e $f_priv) {
			$print->("SASL: refusing to overwrite '$f_priv'", MSGLEVEL_CLIENTERROR);
			return;
		}

		$print->("SASL: generating keypair for '$net'...");
		my $pk = Crypt::PK::ECC->new;
		$pk->generate_key("prime256v1");

		my $priv = $pk->export_key_pem("private");
		my $pub = encode_base64($pk->export_key_raw("public_compressed"), "");

		if (open(my $fh, ">", $f_priv)) {
			chmod(0600, $f_priv);
			print $fh $priv;
			close($fh);
			$print->("SASL: wrote private key to '$f_priv'");
		} else {
			$print->("SASL: could not write '$f_priv': $!", MSGLEVEL_CLIENTERROR);
			return;
		}

		if (open(my $fh, ">", $f_pub)) {
			print $fh $pub."\n";
			close($fh);
		} else {
			$print->("SASL: could not write '$f_pub': $!", MSGLEVEL_CLIENTERROR);
		}

		my $cmdchar = substr(Irssi::settings_get_str("cmdchars"), 0, 1);
		my $cmd = "msg NickServ SET PUBKEY $pub";

		if ($server) {
			$print->("SASL: updating your Irssi settings...");
			$sasl_auth{$net}{user} //= $server->{nick};
			$sasl_auth{$net}{password} = "$f_name.key";
			$sasl_auth{$net}{mech} = $mech;
			cmd_sasl_save(@_);
			$print->("SASL: submitting pubkey to NickServ...");
			$server->command($cmd);
		} else {
			$print->("SASL: update your Irssi settings:");
			$print->("%P".$cmdchar."sasl set $net <nick> $f_name.key $mech");
			$print->("SASL: submit your pubkey to $net:");
			$print->("%P".$cmdchar.$cmd);
		}
	});

	Irssi::command_bind("sasl pubkey" => sub {
		my ($data, $server, $witem) = @_;

		my $arg = $server ? $server->{tag} : $data;

		my $f;
		if (!length $arg) {
			Irssi::print("SASL: please select a server or specify a keyfile path",
						MSGLEVEL_CLIENTERROR);
			return;
		} elsif ($arg =~ m![/.]!) {
			$f = $arg;
		} else {
			if ($sasl_auth{$arg}{mech} eq $mech) {
				$f = $sasl_auth{$arg}{password};
			} else {
				$f = lc "sasl-ecdsa-$arg";
				$f =~ s![ /]+!_!g;
				$f = "$f.key";
			}
		}

		$f = irssi_abspath($f);
		if (!-e $f) {
			Irssi::print("SASL: keyfile '$f' not found", MSGLEVEL_CLIENTERROR);
			return;
		}

		my $pk = eval {Crypt::PK::ECC->new($f)};
		if ($@ || !$pk || !$pk->is_private) {
			Irssi::print("SASL: no private key in file '$f'", MSGLEVEL_CLIENTERROR);
			Irssi::print("(keys using named parameters or PKCS#8 are not yet supported)",
						MSGLEVEL_CLIENTERROR);
			return;
		}

		my $pub = encode_base64($pk->export_key_raw("public_compressed"), "");
		Irssi::print("SASL: loaded keyfile '$f'");
		Irssi::print("SASL: your pubkey is $pub");
	});
} else {
	Irssi::command_bind("sasl keygen" => sub {
		Irssi::print("SASL: cannot '/sasl keygen' as the Perl 'CryptX' module is missing",
					MSGLEVEL_CLIENTERROR);
	});

	Irssi::command_bind("sasl pubkey" => sub {
		Irssi::print("SASL: cannot '/sasl pubkey' as the Perl 'CryptX' module is missing",
					MSGLEVEL_CLIENTERROR);
	});
}

cmd_sasl_load();

# vim: ts=4:sw=4