Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e0c6901

Browse files
committed
Added leading comment and security check.
1 parent 42ded89 commit e0c6901

1 file changed

Lines changed: 28 additions & 5 deletions

File tree

Demo/pysvr/pysvr.c

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
/* A multi-threaded telnet-like server that gives a Python prompt.
2+
3+
Usage: pysvr [port]
4+
5+
For security reasons, it only accepts requests from the current host.
6+
This can still be insecure, but restricts violations from people who
7+
can log in on your machine. Use with caution!
8+
9+
*/
10+
111
#include <stdio.h>
212
#include <stdlib.h>
313
#include <string.h>
@@ -88,8 +98,8 @@ usage()
8898
static void
8999
main_thread(int port)
90100
{
91-
int sock;
92-
struct sockaddr_in addr;
101+
int sock, conn, size;
102+
struct sockaddr_in addr, clientaddr;
93103

94104
sock = socket(PF_INET, SOCK_STREAM, 0);
95105
if (sock < 0) {
@@ -117,16 +127,29 @@ main_thread(int port)
117127
fprintf(stderr, "Listening on port %d...\n", port);
118128

119129
for (;;) {
120-
struct sockaddr_in clientaddr;
121-
int conn, size;
122-
130+
size = sizeof clientaddr;
123131
conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
124132
if (conn < 0) {
125133
oprogname();
126134
perror("can't accept connection from socket");
127135
exit(1);
128136
}
129137

138+
size = sizeof addr;
139+
if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
140+
oprogname();
141+
perror("can't get socket name of connection");
142+
exit(1);
143+
}
144+
if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
145+
oprogname();
146+
perror("connection from non-local host refused");
147+
fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
148+
ntohl(addr.sin_addr.s_addr),
149+
ntohl(clientaddr.sin_addr.s_addr));
150+
close(conn);
151+
continue;
152+
}
130153
create_thread(conn, &clientaddr);
131154
}
132155
}

0 commit comments

Comments
 (0)