Discussion:
Use getservbyname(3) for port numbers
Christian Weisgerber
2018-09-08 08:24:59 UTC
Permalink
[Reposted from ***@openbsd.org]

Is there a reason ssh doesn't consult services(5) for port numbers?

This has irked me forever. I'd rather write ssh -L icb:localhost:icb
instead of ssh -L 7326, wait, 7236, uhm, grep icb /etc/services...

I don't think there is any syntactic ambiguity since Unix sockets
already must contain a '/'.

The patch below adds this:
* Try to resolve a port specification with getservbyname(3) if a
numeric conversion fails.
* Make the "Port" option in ssh_config handle its argument as a
port rather than a plain integer.

All other command line switches and configuration file options
already use a2port().

This passes the existing regression tests.

Index: misc.c
===================================================================
RCS file: /cvs/src/usr.bin/ssh/misc.c,v
retrieving revision 1.131
diff -u -p -r1.131 misc.c
--- misc.c 27 Jul 2018 05:13:02 -0000 1.131
+++ misc.c 30 Aug 2018 23:59:07 -0000
@@ -36,6 +36,7 @@
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
+#include <arpa/inet.h>

#include <ctype.h>
#include <errno.h>
@@ -299,13 +300,16 @@ pwcopy(struct passwd *pw)
int
a2port(const char *s)
{
+ struct servent *se;
long long port;
const char *errstr;

port = strtonum(s, 0, 65535, &errstr);
- if (errstr != NULL)
- return -1;
- return (int)port;
+ if (errstr == NULL)
+ return (int)port;
+ if ((se = getservbyname(s, "tcp")) != NULL)
+ return ntohs(se->s_port);
+ return -1;
}

int
Index: readconf.c
===================================================================
RCS file: /cvs/src/usr.bin/ssh/readconf.c,v
retrieving revision 1.297
diff -u -p -r1.297 readconf.c
--- readconf.c 12 Aug 2018 20:19:13 -0000 1.297
+++ readconf.c 30 Aug 2018 23:14:38 -0000
@@ -1142,7 +1142,20 @@ parse_command:
return 0;

case oPort:
- intptr = &options->port;
+ arg = strdelim(&s);
+ if (!arg || *arg == '\0')
+ fatal("%.200s line %d: Missing argument.",
+ filename, linenum);
+ value = a2port(arg);
+ if (value <= 0)
+ fatal("%.200s line %d: Bad port '%s'.",
+ filename, linenum, arg);
+ if (*activep && options->port == -1)
+ options->port = value;
+ break;
+
+ case oConnectionAttempts:
+ intptr = &options->connection_attempts;
parse_int:
arg = strdelim(&s);
if ((errstr = atoi_err(arg, &value)) != NULL)
@@ -1151,10 +1164,6 @@ parse_int:
if (*activep && *intptr == -1)
*intptr = value;
break;
-
- case oConnectionAttempts:
- intptr = &options->connection_attempts;
- goto parse_int;

case oCiphers:
arg = strdelim(&s);
--
Christian "naddy" Weisgerber ***@mips.inka.de
Loading...