Advertisement
Guest User

Untitled

a guest
Oct 21st, 2018
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 28.94 KB | None | 0 0
  1. // @see https://www.ietf.org/rfc/rfc1928.txt
  2. // @see https://tools.ietf.org/html/rfc1929
  3.  
  4. #define _GNU_SOURCE
  5.  
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <unistd.h>
  9. #include <string.h>
  10. #include <time.h>
  11. #include <errno.h>
  12. #include <signal.h>
  13.  
  14. #include <netinet/in.h>
  15. #include <sys/types.h>
  16. #include <sys/socket.h>
  17. #include <netdb.h>
  18. #include <sys/epoll.h>
  19. #include <arpa/inet.h>
  20.  
  21. #define FPRINTF(...) fprintf(logFile, __VA_ARGS__); fflush(logFile)
  22. #ifdef DEBUG
  23. #define FPRINTF_DEBUG(...) fprintf(logFile, __VA_ARGS__); fflush(logFile)
  24. #else
  25. #define FPRINTF_DEBUG(...)
  26. #endif
  27.  
  28. #define HIGHLIGHT_START "\033[32;49;1m"
  29. #define HIGHLIGHT_END   "\033[39;49;0m"
  30.  
  31. #define MAX_CONNS 500
  32. #define CONN_BUF_LEN 4096
  33. struct connBuf {
  34.     uint16_t    expectedBytes;
  35.     uint16_t    bufUsed;
  36.     uint8_t     *bufp;
  37.     uint8_t     buf[CONN_BUF_LEN];
  38. };
  39. struct conn {
  40.     int             fd;
  41.     uint32_t        expectedEvents;
  42.     void            (*callback)(struct conn *);
  43.     void            (*nextCallback)(struct conn *);
  44.     struct conn     *assocConn;
  45.     struct connBuf  *buf;
  46.     uint8_t         blocked;
  47. #ifdef DEBUG
  48.     char ip[NI_MAXHOST];
  49.     char port[NI_MAXSERV];
  50. #endif
  51. };
  52.  
  53. #define CMD_CONNECT         1
  54. #define CMD_BIND            2
  55. #define CMD_UDP_ASSOCIATE   3
  56.  
  57. #define CMD_REPLY_SUCCESS                   0
  58. #define CMD_REPLY_GENERRAL_SOCKS_ERROR      1
  59. #define CMD_REPLY_NOT_SUPPORTED             7
  60. #define CMD_REPLY_ADDR_TYPE_NOT_SUPPORTED   8
  61.  
  62. #define ADDR_TYPE_IPV4       1
  63. #define ADDR_TYPE_DOMAINNAME 3
  64. #define ADDR_TYPE_IPV6       4
  65.  
  66. #define AUTH_METHOD_NONE      0
  67. #define AUTH_METHOD_USER_PASS 2
  68. #define AUTH_METHOD_USER_PASS_VER 1
  69. #define AUTH_METHOD_USER_PASS_SUCCESS 0
  70. #define AUTH_METHOD_USER_PASS_FAILED  1
  71.  
  72. #define SOCKS5_VER 5
  73.  
  74. // GLOBAL VARS
  75. struct conn clientConnList[MAX_CONNS];
  76. struct conn remoteConnList[MAX_CONNS];
  77. struct connBuf bufPool[MAX_CONNS];
  78. int         epfd;
  79. FILE        *logFile;
  80. char        *username;
  81. char        *password;
  82. uint8_t     usernameLen;
  83. uint8_t     passwordLen;
  84. // GLOBAL VARS END
  85.  
  86. void help()
  87. {
  88.     printf(
  89.         "usage: ./my-socks5 [-u username] [-p password] [-P port] [-F] [-h]\n"
  90.         "       -u  username, required\n"
  91.         "       -p  password, required\n"
  92.         "       -P  port, default 5555\n"
  93.         "       -F  run in foreground\n"
  94.         "       -h  usage info\n"
  95.     );
  96. }
  97.  
  98. void signal_handler(int signo)
  99. {
  100.     if (signo == SIGINT) {
  101.         FPRINTF("caught SIGINT, exit\n");
  102.     }
  103.     if (signo == SIGTERM) {
  104.         FPRINTF("caught SIGTERM, exit\n");
  105.     }
  106.     exit(0);
  107. }
  108.  
  109. void initConns()
  110. {
  111.     int i;
  112.     for (i = 0; i < MAX_CONNS; i++) {
  113.         clientConnList[i].fd  = -1;
  114.         clientConnList[i].buf = bufPool + i;
  115.         remoteConnList[i].fd  = -1;
  116.     }
  117. }
  118.  
  119. void closeConn(struct conn *conn)
  120. {
  121.     if (conn->fd == -1) {
  122.         return;
  123.     }
  124.  
  125.     if (epoll_ctl(epfd, EPOLL_CTL_DEL, conn->fd, NULL) == -1) {
  126.         FPRINTF("epoll_ctl del fd error: %s\n", strerror(errno));
  127.         exit(1);
  128.     }
  129.     close(conn->fd);
  130.     conn->fd = -1;
  131. }
  132.  
  133. struct conn *getAFreeClientConn()
  134. {
  135.     int i;
  136.     for (i = 0; i < MAX_CONNS; i++) {
  137.         if (clientConnList[i].fd == -1) {
  138.             return clientConnList + i;
  139.         }
  140.     }
  141.     return NULL;
  142. }
  143.  
  144. struct conn *getAFreeRemoteConn()
  145. {
  146.     int i;
  147.     for (i = 0; i < MAX_CONNS; i++) {
  148.         if (remoteConnList[i].fd == -1) {
  149.             return remoteConnList + i;
  150.         }
  151.     }
  152.     return NULL;
  153. }
  154.  
  155. void resetConnBuf(struct connBuf *connBuf)
  156. {
  157.     connBuf->expectedBytes = 0;
  158.     connBuf->bufUsed = 0;
  159.     connBuf->bufp    = NULL;
  160. }
  161.  
  162. void readN(struct conn *conn)
  163. {
  164.     struct connBuf *connBuf = conn->buf;
  165.  
  166.     int n = read(conn->fd, connBuf->buf + connBuf->bufUsed, connBuf->expectedBytes);
  167.  
  168.     // CONN_BUF_LEN means read as much as possible
  169.     if (connBuf->expectedBytes == CONN_BUF_LEN) {
  170.         if (n > 0) {
  171.             connBuf->bufUsed += n;
  172.             return conn->nextCallback(conn);
  173.         }
  174.         if (n == 0) {
  175.             FPRINTF_DEBUG("conn closed\n");
  176.             goto closeConn;
  177.         }
  178.         // n < 0
  179.         if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR) {
  180.             return conn->nextCallback(conn);
  181.         }
  182.         goto error;
  183.     }
  184.  
  185.     if (n > 0) {
  186.         connBuf->bufUsed += n;
  187.         connBuf->expectedBytes -= n;
  188.         if (connBuf->expectedBytes > 0) {
  189.             return;
  190.         }
  191.         return conn->nextCallback(conn);
  192.     }
  193.  
  194.     if (n == 0) {
  195.         FPRINTF_DEBUG("conn closed\n");
  196.         goto closeConn;
  197.     }
  198.  
  199.     // n < 0
  200.     if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR) {
  201.         return;
  202.     }
  203. error:
  204.     FPRINTF("readN error: %s\n", strerror(errno));
  205. closeConn:
  206.     if (conn->assocConn) {
  207.         closeConn(conn->assocConn);
  208.     }
  209.     closeConn(conn);
  210. }
  211.  
  212. // before writeN, conn expect EPOLLIN
  213. // if write done first try, call the nextCallback
  214. // if not, modify conn expect to EPOLLOUT, callback to writeN
  215. // when writeN complete, change back to EPOLLIN, call nextCallback
  216. void writeN(struct conn *conn)
  217. {
  218.     struct connBuf *connBuf = conn->buf;
  219.  
  220.     FPRINTF_DEBUG("want write %d bytes\n", connBuf->expectedBytes);
  221.     int n = write(conn->fd, connBuf->bufp, connBuf->expectedBytes);
  222.     FPRINTF_DEBUG("write return %d\n", n);
  223.     if (n > 0) {
  224.         connBuf->bufp += n;
  225.         connBuf->expectedBytes -= n;
  226.         if (connBuf->expectedBytes == 0) {
  227.             if (conn->expectedEvents & EPOLLOUT) {
  228.                 FPRINTF_DEBUG("write done, watch EPOLLIN\n");
  229.                 conn->expectedEvents = EPOLLIN;
  230.                 conn->callback       = NULL;
  231.                 struct epoll_event ev;
  232.                 ev.events   = EPOLLIN;
  233.                 ev.data.ptr = conn;
  234.                 if (epoll_ctl(epfd, EPOLL_CTL_MOD, conn->fd, &ev) == -1) {
  235.                     FPRINTF("epoll_ctl mod error: %s\n", strerror(errno));
  236.                     exit(1);
  237.                 }
  238.             }
  239.             return conn->nextCallback(conn);
  240.         }
  241.         goto epollout;
  242.     }
  243.  
  244.     if (n == 0) {
  245.         goto epollout;
  246.     }
  247.  
  248.     // n < 0
  249.     if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR) {
  250.         goto epollout;
  251.     }
  252.     FPRINTF("writeN error: %s\n", strerror(errno));
  253.  
  254.     if (conn->assocConn) {
  255.         closeConn(conn->assocConn);
  256.     }
  257.     closeConn(conn);
  258.     return;
  259.  
  260. epollout:
  261.     FPRINTF_DEBUG(HIGHLIGHT_START "write not complete, wait EPOLLOUT" HIGHLIGHT_END "\n");
  262.     if (conn->expectedEvents & EPOLLOUT) {
  263.         return;
  264.     }
  265.  
  266.     conn->expectedEvents = EPOLLOUT;
  267.     conn->callback       = writeN;
  268.  
  269.     struct epoll_event ev;
  270.     ev.events   = EPOLLOUT;
  271.     ev.data.ptr = conn;
  272.     if (epoll_ctl(epfd, EPOLL_CTL_MOD, conn->fd, &ev) == -1) {
  273.         FPRINTF("epoll_ctl mod error: %s\n", strerror(errno));
  274.         exit(1);
  275.     }
  276. }
  277.  
  278. void delayCloseConn(struct conn *conn)
  279. {
  280.     FPRINTF_DEBUG("delay close conn\n");
  281.  
  282.     conn->callback     = readN;
  283.     conn->nextCallback = NULL;
  284.     resetConnBuf(conn->buf);
  285.     conn->buf->expectedBytes = 0;
  286. }
  287.  
  288. /*
  289.     Request:
  290.     +----+-----+-------+------+----------+----------+
  291.     |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
  292.     +----+-----+-------+------+----------+----------+
  293.     | 1  |  1  | X'00' |  1   | Variable |    2     |
  294.     +----+-----+-------+------+----------+----------+
  295.     Reply:
  296.     +----+-----+-------+------+----------+----------+
  297.     |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
  298.     +----+-----+-------+------+----------+----------+
  299.     | 1  |  1  | X'00' |  1   | Variable |    2     |
  300.     +----+-----+-------+------+----------+----------+
  301. */
  302. void cmdReplyError(struct conn *conn, int8_t err)
  303. {
  304.     FPRINTF_DEBUG("cmd reply error: %d\n", err);
  305.  
  306.     conn->buf->buf[1] = err;
  307.     conn->buf->expectedBytes = conn->buf->bufUsed;
  308.     conn->buf->bufp = conn->buf->buf;
  309.     conn->callback     = NULL;
  310.     conn->nextCallback = delayCloseConn;
  311.     writeN(conn);
  312. }
  313.  
  314. void processCommandBind(struct conn *conn)
  315. {
  316.     cmdReplyError(conn, CMD_REPLY_NOT_SUPPORTED);
  317. }
  318.  
  319. void processCommandUdpAssociate(struct conn *conn)
  320. {
  321.     cmdReplyError(conn, CMD_REPLY_NOT_SUPPORTED);
  322. }
  323.  
  324. void proxyToRemoteTargetDone(struct conn *remoteConn);
  325. void proxyToRemoteTarget(struct conn *clientConn);
  326. void proxyToClientDone(struct conn *clientConn);
  327. void proxyToClient(struct conn *remoteConn);
  328.  
  329. void proxyToRemoteTargetDone(struct conn *remoteConn)
  330. {
  331.     FPRINTF_DEBUG("client send data to remote done\n");
  332.  
  333.     // client
  334.     remoteConn->assocConn->blocked    = 0;
  335.     // remote
  336.     remoteConn->callback     = readN;
  337.     remoteConn->nextCallback = proxyToClient;
  338.     resetConnBuf(remoteConn->buf);
  339.     remoteConn->buf->expectedBytes = CONN_BUF_LEN;
  340. }
  341.  
  342. void proxyToRemoteTarget(struct conn *clientConn)
  343. {
  344.     FPRINTF_DEBUG("client send data to remote, data length: ");
  345.  
  346.     if (clientConn->buf->bufUsed == 0) {
  347.         FPRINTF_DEBUG("0\n");
  348.         return;
  349.     }
  350.  
  351.     FPRINTF_DEBUG("%d\n", clientConn->buf->bufUsed);
  352.  
  353.     clientConn->blocked = 1; // ignore clientConn events
  354.     struct conn *remoteConn = clientConn->assocConn;
  355.     remoteConn->buf->expectedBytes = remoteConn->buf->bufUsed;
  356.     remoteConn->buf->bufp = remoteConn->buf->buf;
  357.     remoteConn->callback     = NULL;
  358.     remoteConn->nextCallback = proxyToRemoteTargetDone;
  359.     writeN(remoteConn);
  360. }
  361.  
  362. void proxyToClientDone(struct conn *clientConn)
  363. {
  364.     FPRINTF_DEBUG("remote send data to client done\n");
  365.  
  366.     // remote
  367.     clientConn->assocConn->blocked = 0;
  368.     // client
  369.     clientConn->callback     = readN;
  370.     clientConn->nextCallback = proxyToRemoteTarget;
  371.     resetConnBuf(clientConn->buf);
  372.     clientConn->buf->expectedBytes = CONN_BUF_LEN;
  373. }
  374.  
  375. void proxyToClient(struct conn *remoteConn)
  376. {
  377.     FPRINTF_DEBUG("remote send data to client, data length: ");
  378.  
  379.     if (remoteConn->buf->bufUsed == 0) {
  380.         FPRINTF_DEBUG("0\n");
  381.         return;
  382.     }
  383.  
  384.     FPRINTF_DEBUG("%d\n", remoteConn->buf->bufUsed);
  385.  
  386.     remoteConn->blocked = 1; // ignore remoteConn events
  387.     struct conn *clientConn = remoteConn->assocConn;
  388.     clientConn->buf->expectedBytes = clientConn->buf->bufUsed;
  389.     clientConn->buf->bufp = clientConn->buf->buf;
  390.     clientConn->callback     = NULL;
  391.     clientConn->nextCallback = proxyToClientDone;
  392.     writeN(clientConn);
  393. }
  394.  
  395. void startProxy(struct conn *clientConn)
  396. {
  397.     FPRINTF_DEBUG("start proxy\n");
  398.  
  399.     clientConn->callback     = readN;
  400.     clientConn->nextCallback = proxyToRemoteTarget;
  401.     resetConnBuf(clientConn->buf);
  402.     clientConn->buf->expectedBytes = CONN_BUF_LEN;
  403.  
  404.     struct conn *remoteConn = clientConn->assocConn;
  405.     remoteConn->expectedEvents = EPOLLIN;
  406.     remoteConn->callback       = readN;
  407.     remoteConn->nextCallback   = proxyToClient;
  408.  
  409.     struct epoll_event ev;
  410.     ev.events = EPOLLIN;
  411.     ev.data.ptr = remoteConn;
  412.     if (epoll_ctl(epfd, EPOLL_CTL_ADD, remoteConn->fd, &ev) == -1) {
  413.         FPRINTF("epoll_ctl add error: %s\n", strerror(errno));
  414.         exit(1);
  415.     }
  416. }
  417.  
  418. void confirmConnectedToRemoteTarget(struct conn *remoteConn)
  419. {
  420.     int optval = 0;
  421.     socklen_t optlen = sizeof(optval);
  422.     int ret = getsockopt(remoteConn->fd, SOL_SOCKET, SO_ERROR, &optval, &optlen);
  423.     if (ret == -1) {
  424.         FPRINTF("getsockopt error: %s\n", strerror(errno));
  425.         goto error;
  426.     }
  427.     if (optval != 0) {
  428.         FPRINTF("connect to remote target error: %s\n", strerror(errno));
  429.         goto error;
  430.     }
  431.     // optval = 0, connect success
  432.     struct sockaddr addr;
  433.     socklen_t addrlen = sizeof(addr);
  434.     if (getsockname(remoteConn->fd, (struct sockaddr *)&addr, &addrlen) == -1) {
  435.         FPRINTF("getsockname error: %s\n", strerror(errno));
  436.         goto error;
  437.     }
  438.     optval = 1;
  439.     if (setsockopt(remoteConn->fd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) == -1) {
  440.         FPRINTF("setsockopt keepalive error: %s\n", strerror(errno));
  441.         goto error;
  442.     }
  443.     if (epoll_ctl(epfd, EPOLL_CTL_DEL, remoteConn->fd, NULL) == -1) {
  444.         FPRINTF("epoll_ctl del fd error: %s\n", strerror(errno));
  445.         exit(1);
  446.     }
  447.  
  448.     FPRINTF_DEBUG(HIGHLIGHT_START "connected to remote target success" HIGHLIGHT_END "\n");
  449.     FPRINTF_DEBUG("response client\n");
  450.  
  451.     struct conn *clientConn = remoteConn->assocConn;
  452.     uint8_t *buf = clientConn->buf->buf;
  453.     buf[1] = CMD_REPLY_SUCCESS;
  454.     if (addr.sa_family == AF_INET) {
  455.         buf[3] = ADDR_TYPE_IPV4;
  456.         struct sockaddr_in *addr_in = (struct sockaddr_in *)&addr;
  457.         memcpy(buf + 4, &addr_in->sin_addr.s_addr, 4);
  458.         memcpy(buf + 8, &addr_in->sin_port, 2);
  459.         clientConn->buf->expectedBytes = 10; // 4 + 4 + 2
  460.     } else {
  461.         buf[3] = ADDR_TYPE_IPV6;
  462.         struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)&addr;
  463.         memcpy(buf + 4, &addr_in6->sin6_addr.s6_addr, 16);
  464.         memcpy(buf + 20, &addr_in6->sin6_port, 2);
  465.         clientConn->buf->expectedBytes = 22; // 4 + 16 + 2
  466.     }
  467.  
  468.     clientConn->buf->bufp = clientConn->buf->buf;
  469.     clientConn->callback     = NULL;
  470.     clientConn->nextCallback = startProxy;
  471.     writeN(clientConn);
  472.     return;
  473.  
  474. error:
  475.     closeConn(remoteConn);
  476.     cmdReplyError(remoteConn->assocConn, CMD_REPLY_GENERRAL_SOCKS_ERROR);
  477. }
  478.  
  479. void processCommandConnect(struct conn *conn)
  480. {
  481.     char hbuf[NI_MAXHOST];
  482.     char sbuf[NI_MAXSERV];
  483.     struct addrinfo hints;
  484.     struct addrinfo *result, *rp;
  485.     int err;
  486.  
  487.     memset(&hints, 0, sizeof(hints));
  488.     hints.ai_socktype = SOCK_STREAM;
  489.     hints.ai_flags    = AI_NUMERICSERV;
  490.  
  491.     int addrType = conn->buf->buf[3];
  492.     uint8_t domainNameLen;
  493.     switch (addrType) {
  494.     case ADDR_TYPE_IPV4:
  495.         inet_ntop(AF_INET, conn->buf->buf + 4, hbuf, NI_MAXHOST);
  496.         sprintf(sbuf, "%d", ntohs(*((uint16_t *)(conn->buf->buf + 4 + 4))));
  497.         hints.ai_family = AF_INET;
  498.         hints.ai_flags |= AI_NUMERICHOST;
  499.         break;
  500.     case ADDR_TYPE_DOMAINNAME:
  501.         domainNameLen = *((uint8_t *)(conn->buf->buf + 4));
  502.         memcpy(hbuf, conn->buf->buf + 4 + 1, domainNameLen);
  503.         hbuf[domainNameLen] = 0;
  504.         sprintf(sbuf, "%d", ntohs(*((uint16_t *)(conn->buf->buf + 4 + 1 + domainNameLen))));
  505.         hints.ai_family = AF_UNSPEC;
  506.         break;
  507.     case ADDR_TYPE_IPV6:
  508.         inet_ntop(AF_INET6, conn->buf->buf + 4, hbuf, NI_MAXHOST);
  509.         sprintf(sbuf, "%d", ntohs(*((uint16_t *)(conn->buf->buf + 4 + 16))));
  510.         hints.ai_family = AF_INET6;
  511.         hints.ai_flags |= AI_NUMERICHOST;
  512.         break;
  513.     }
  514.  
  515. #ifdef DEBUG
  516.     FPRINTF_DEBUG(HIGHLIGHT_START "clinet want to connect %s:%s" HIGHLIGHT_END "\n", hbuf, sbuf);
  517. #endif
  518.  
  519.     err = getaddrinfo(hbuf, sbuf, &hints, &result);
  520.     if (err != 0) {
  521.         FPRINTF("getaddrinfo error: %s\n", gai_strerror(err));
  522.         cmdReplyError(conn, CMD_REPLY_GENERRAL_SOCKS_ERROR);
  523.         return;
  524.     }
  525.  
  526.     int remotefd;
  527.     struct conn *remoteConn = getAFreeRemoteConn();
  528.     for (rp = result; rp != NULL; rp = rp->ai_next) {
  529.         remotefd = socket(rp->ai_family, rp->ai_socktype | SOCK_NONBLOCK, rp->ai_protocol);
  530.         if (remotefd == -1) {
  531.             continue;
  532.         }
  533.         if (connect(remotefd, rp->ai_addr, rp->ai_addrlen) != -1) {
  534.             FPRINTF("!!!connect to remote target immediately!!!\n");
  535.             exit(1);
  536.         }
  537.         if (errno == EINPROGRESS) {
  538. #ifdef DEBUG
  539.     err = getnameinfo(rp->ai_addr, rp->ai_addrlen, remoteConn->ip, NI_MAXHOST, remoteConn->port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV);
  540.     if (err != 0) {
  541.         FPRINTF("getnamedinfo error: %s\n", gai_strerror(err));
  542.         exit(1);
  543.     }
  544.     FPRINTF_DEBUG(HIGHLIGHT_START "actually connect %s:%s" HIGHLIGHT_END "\n", remoteConn->ip, remoteConn->port);
  545. #endif
  546.             break;
  547.         }
  548.         close(remotefd);
  549.     }
  550.     freeaddrinfo(result);
  551.     if (rp == NULL) {
  552.         FPRINTF("connect failed\n");
  553.         cmdReplyError(conn, CMD_REPLY_GENERRAL_SOCKS_ERROR);
  554.         return;
  555.     }
  556.  
  557.     remoteConn->fd             = remotefd;
  558.     remoteConn->expectedEvents = EPOLLOUT;
  559.     remoteConn->callback       = confirmConnectedToRemoteTarget;
  560.     remoteConn->blocked        = 0;
  561.     remoteConn->buf            = conn->buf;
  562.  
  563.     struct epoll_event ev;
  564.     ev.events   = EPOLLOUT;
  565.     ev.data.ptr = remoteConn;
  566.     if (epoll_ctl(epfd, EPOLL_CTL_ADD, remotefd, &ev) == -1) {
  567.         remoteConn->fd = -1;
  568.         close(remotefd);
  569.         FPRINTF("epoll_ctl add error: %s\n", strerror(errno));
  570.         cmdReplyError(conn, CMD_REPLY_GENERRAL_SOCKS_ERROR);
  571.         return;
  572.     }
  573.  
  574.     remoteConn->assocConn = conn;
  575.     conn->assocConn       = remoteConn;
  576. }
  577.  
  578. void dispatchCommand(struct conn *conn)
  579. {
  580.     FPRINTF_DEBUG("dispatch command\n");
  581.  
  582.     if (conn->buf->expectedBytes == CONN_BUF_LEN) {
  583.         // address type not supported
  584.         cmdReplyError(conn, CMD_REPLY_ADDR_TYPE_NOT_SUPPORTED);
  585.         return;
  586.     }
  587.  
  588.     uint8_t *buf = (uint8_t *)conn->buf->buf;
  589.     switch (buf[1]) {
  590.     case CMD_CONNECT:
  591.         return processCommandConnect(conn);
  592.     case CMD_BIND:
  593.         return processCommandBind(conn);
  594.     case CMD_UDP_ASSOCIATE:
  595.         return processCommandUdpAssociate(conn);
  596.     }
  597. }
  598.  
  599. void processCommandCalcLen(struct conn *conn)
  600. {
  601.     FPRINTF_DEBUG("got client command\n");
  602.  
  603.     uint8_t *buf = (uint8_t *)conn->buf->buf;
  604.     if (buf[0] != SOCKS5_VER) {
  605.         goto badFormat;
  606.     }
  607.  
  608.     uint8_t cmd = buf[1];
  609.     if (cmd != CMD_CONNECT && cmd != CMD_BIND && cmd != CMD_UDP_ASSOCIATE) {
  610.         goto badFormat;
  611.     }
  612.  
  613.     uint8_t addrType = buf[3];
  614.     uint16_t dstAddrLen;
  615.     if (addrType == ADDR_TYPE_IPV4) {
  616.         dstAddrLen = 4 - 1;
  617.     } else if (addrType == ADDR_TYPE_DOMAINNAME) {
  618.         dstAddrLen = buf[4];
  619.     } else if (addrType == ADDR_TYPE_IPV6) {
  620.         dstAddrLen = 16 - 1;
  621.     } else {
  622.         dstAddrLen = CONN_BUF_LEN - 2;
  623.     }
  624.  
  625.     FPRINTF_DEBUG("prepare to read command arguments\n");
  626.  
  627.     conn->buf->expectedBytes = dstAddrLen + 2;
  628.     conn->nextCallback = dispatchCommand;
  629.     return;
  630.  
  631. badFormat:
  632.     FPRINTF("request format wrong\n");
  633.     closeConn(conn);
  634. }
  635.  
  636. void startProcessCommand(struct conn *conn)
  637. {
  638.     FPRINTF_DEBUG("wait for client command\n");
  639.  
  640.     conn->callback     = readN;
  641.     conn->nextCallback = processCommandCalcLen;
  642.     resetConnBuf(conn->buf);
  643.     conn->buf->expectedBytes = 4 + 1;
  644. }
  645.  
  646. /*
  647.     +----+------+----------+------+----------+
  648.     |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
  649.     +----+------+----------+------+----------+
  650.     | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
  651.     +----+------+----------+------+----------+
  652. */
  653. void doAuth(struct conn *conn)
  654. {
  655.     FPRINTF_DEBUG("got username/password, check it\n");
  656.  
  657.     uint8_t *buf = (uint8_t *)conn->buf->buf;
  658.     uint8_t ulen = buf[1];
  659.     uint8_t plen = buf[2 + ulen];
  660.     void (*nextCallback)(struct conn *);
  661.  
  662.     if (ulen == usernameLen
  663.         && plen == passwordLen
  664.         && memcmp(buf + 2, username, ulen) == 0
  665.         && memcmp(buf + 2 + ulen + 1, password, plen) == 0
  666.     ) {
  667.         buf[1] = AUTH_METHOD_USER_PASS_SUCCESS;
  668.         nextCallback = startProcessCommand;
  669.         FPRINTF_DEBUG(HIGHLIGHT_START "username/password OK" HIGHLIGHT_END "\n");
  670.     } else {
  671.         buf[1] = AUTH_METHOD_USER_PASS_FAILED;
  672.         nextCallback = delayCloseConn;
  673.         FPRINTF_DEBUG(HIGHLIGHT_START "auth failed" HIGHLIGHT_END "\n");
  674.     }
  675.  
  676.     FPRINTF_DEBUG("response client\n");
  677.  
  678.     conn->buf->expectedBytes = 2;
  679.     conn->buf->bufp = buf;
  680.     conn->callback     = NULL;
  681.     conn->nextCallback = nextCallback;
  682.     writeN(conn);
  683. }
  684.  
  685. void authPasswordCalcLen(struct conn *conn)
  686. {
  687.     FPRINTF_DEBUG("prepare to read password\n");
  688.  
  689.     uint8_t *buf = (uint8_t *)conn->buf->buf;
  690.     uint8_t plen = buf[2 + buf[1]];
  691.  
  692.     if (plen == 0) {
  693.         FPRINTF("username/password request format wrong\n");
  694.         closeConn(conn);
  695.         return;
  696.     }
  697.  
  698.     conn->buf->expectedBytes = plen;
  699.     conn->nextCallback = doAuth;
  700. }
  701.  
  702. void authUsernameCalcLen(struct conn *conn)
  703. {
  704.     FPRINTF_DEBUG("prepare to read username\n");
  705.  
  706.     uint8_t *buf = (uint8_t *)conn->buf->buf;
  707.  
  708.     if (buf[0] != AUTH_METHOD_USER_PASS_VER || buf[1] == 0) {
  709.         FPRINTF("username/password request format wrong\n");
  710.         closeConn(conn);
  711.         return;
  712.     }
  713.  
  714.     conn->buf->expectedBytes = buf[1] + 1;
  715.     conn->nextCallback = authPasswordCalcLen;
  716. }
  717.  
  718. void startAuth(struct conn *conn)
  719. {
  720.     FPRINTF_DEBUG("wait for client username/password message\n");
  721.  
  722.     conn->callback     = readN;
  723.     conn->nextCallback = authUsernameCalcLen;
  724.     resetConnBuf(conn->buf);
  725.     conn->buf->expectedBytes = 2;
  726. }
  727.  
  728. void selectAuthMethod(struct conn *conn)
  729. {
  730.     FPRINTF_DEBUG("got client auth methods\n");
  731.  
  732.     uint8_t *buf = (uint8_t *)conn->buf->buf;
  733.  
  734.     int i;
  735.     uint8_t method = 0xFF;
  736.     void (*nextCallback)(struct conn *);
  737.     if (username && password) {
  738.         for (i = 0; i < buf[1]; i++) {
  739.             if (buf[i + 2] == AUTH_METHOD_USER_PASS) {
  740.                 FPRINTF_DEBUG("client support username/password authentication, good.\n");
  741.                 method = AUTH_METHOD_USER_PASS;
  742.                 nextCallback = startAuth;
  743.                 break;
  744.             }
  745.         }
  746.     } else {
  747.         for (i = 0; i < buf[1]; i++) {
  748.             if (buf[i + 2] == AUTH_METHOD_NONE) {
  749.                 FPRINTF_DEBUG("client expects no authentication required, ok, continue\n");
  750.                 method = AUTH_METHOD_NONE;
  751.                 nextCallback = startProcessCommand;
  752.                 break;
  753.             }
  754.         }
  755.     }
  756.     if (method == 0xFF) {
  757.         nextCallback = delayCloseConn;
  758.     }
  759.  
  760. #ifdef DEBUG
  761.     if (method == 0xFF) {
  762.         FPRINTF_DEBUG("no acceptable methods\n");
  763.     }
  764. #endif
  765.  
  766.     FPRINTF_DEBUG("response client\n");
  767.  
  768.     buf[1] = method;
  769.     conn->buf->expectedBytes = 2;
  770.     conn->buf->bufp = buf;
  771.     conn->callback     = NULL;
  772.     conn->nextCallback = nextCallback;
  773.     writeN(conn);
  774. }
  775.  
  776. /*
  777.     +----+----------+----------+
  778.     |VER | NMETHODS | METHODS  |
  779.     +----+----------+----------+
  780.     | 1  |    1     | 1 to 255 |
  781.     +----+----------+----------+
  782. */
  783. void selectAuthMethodCalcLen(struct conn *conn)
  784. {
  785.     FPRINTF_DEBUG("prepare to read auth methods\n");
  786.  
  787.     uint8_t *buf = (uint8_t *)conn->buf->buf;
  788.     if (buf[0] != SOCKS5_VER || buf[1] == 0) {
  789.         FPRINTF("version identifier/method selection message format wrong\n");
  790.         closeConn(conn);
  791.         return;
  792.     }
  793.  
  794.     conn->buf->expectedBytes = buf[1];
  795.     conn->nextCallback = selectAuthMethod;
  796. }
  797.  
  798. void acceptClient(struct conn *listeningConn)
  799. {
  800.     FPRINTF_DEBUG(HIGHLIGHT_START "accept client" HIGHLIGHT_END "\n");
  801.  
  802.     struct sockaddr addr;
  803.     socklen_t addrlen = sizeof(addr);
  804.  
  805.     int cfd = accept4(listeningConn->fd, &addr, &addrlen, SOCK_NONBLOCK);
  806.     if (cfd == -1) {
  807.         FPRINTF("accept4 error: %s", strerror(errno));
  808.         return;
  809.     }
  810.  
  811.     struct conn *conn = getAFreeClientConn();
  812.     if (conn == NULL) {
  813.         close(cfd);
  814.         FPRINTF("too many conns, drop client\n");
  815.         return;
  816.     }
  817.  
  818.     int optval = 1;
  819.     if (setsockopt(cfd, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) == -1) {
  820.         close(cfd);
  821.         FPRINTF("setsockopt keepalive error: %s\n", strerror(errno));
  822.         return;
  823.     }
  824.  
  825. #ifdef DEBUG
  826.     int err = getnameinfo(&addr, addrlen, conn->ip, NI_MAXHOST, conn->port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV);
  827.     if (err != 0) {
  828.         close(cfd);
  829.         FPRINTF("getnamedinfo error: %s\n", gai_strerror(err));
  830.         return;
  831.     }
  832.     FPRINTF_DEBUG(HIGHLIGHT_START "accept %s:%s" HIGHLIGHT_END "\n", conn->ip, conn->port);
  833. #endif
  834.  
  835.     conn->fd             = cfd;
  836.     conn->expectedEvents = EPOLLIN;
  837.     conn->callback       = readN;
  838.     conn->nextCallback   = selectAuthMethodCalcLen;
  839.     conn->assocConn      = NULL;
  840.     conn->blocked        = 0;
  841.     resetConnBuf(conn->buf);
  842.     conn->buf->expectedBytes = 2;
  843.  
  844.     struct epoll_event ev;
  845.     ev.events   = EPOLLIN;
  846.     ev.data.ptr = conn;
  847.     if (epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev) == -1) {
  848.         conn->fd = -1;
  849.         close(cfd);
  850.         FPRINTF("epoll_ctl add error: %s\n", strerror(errno));
  851.     }
  852. }
  853.  
  854. void start(int sfd)
  855. {
  856.     initConns();
  857.  
  858.     struct conn listeningConn;
  859.     listeningConn.fd             = sfd;
  860.     listeningConn.expectedEvents = EPOLLIN;
  861.     listeningConn.callback       = acceptClient;
  862.     listeningConn.blocked        = 0;
  863.  
  864.     struct epoll_event ev;
  865.     ev.events   = EPOLLIN;
  866.     ev.data.ptr = &listeningConn;
  867.     if (epoll_ctl(epfd, EPOLL_CTL_ADD, sfd, &ev) == -1) {
  868.         FPRINTF("epoll_ctl add error: %s\n", strerror(errno));
  869.         exit(1);
  870.     }
  871.  
  872.     struct epoll_event evList[1 + MAX_CONNS * 2];
  873.     int ready;
  874.     int i;
  875.     struct conn *conn;
  876.     while (1) {
  877.         ready = epoll_wait(epfd, evList, MAX_CONNS * 2 + 1, 60000);
  878.         if (ready == -1) {
  879.             if (errno == EINTR) {
  880.                 continue;
  881.             }
  882.             FPRINTF("epoll_wait error: %s\n", strerror(errno));
  883.             exit(1);
  884.         }
  885.         FPRINTF_DEBUG("epoll_wait return %d\n", ready);
  886.         for (i = 0; i < ready; i++) {
  887.             conn = (struct conn *)(evList[i].data.ptr);
  888. #ifdef DEBUG
  889.     if (conn->fd != sfd) {
  890.         FPRINTF_DEBUG(HIGHLIGHT_START);
  891.         if (conn->assocConn) {
  892.             FPRINTF_DEBUG("%s:%s <--> %s:%s expects", conn->ip, conn->port, conn->assocConn->ip, conn->assocConn->port);
  893.         } else {
  894.             FPRINTF_DEBUG("%s:%s expects", conn->ip, conn->port);
  895.         }
  896.         if (conn->expectedEvents & EPOLLIN) {
  897.             FPRINTF_DEBUG(" EPOLLIN");
  898.         }
  899.         if (conn->expectedEvents & EPOLLOUT) {
  900.             FPRINTF_DEBUG(" EPOLLOUT");
  901.         }
  902.         FPRINTF_DEBUG(", now it got");
  903.         if (evList[i].events & EPOLLIN) {
  904.             FPRINTF_DEBUG(" EPOLLIN");
  905.         }
  906.         if (evList[i].events & EPOLLOUT) {
  907.             FPRINTF_DEBUG(" EPOLLOUT");
  908.         }
  909.         FPRINTF_DEBUG(HIGHLIGHT_END "\n");
  910.     }
  911. #endif
  912.             if (conn->fd == -1) {
  913.                 FPRINTF_DEBUG("conn closed, skip this conn\n");
  914.                 continue;
  915.             }
  916.             if (conn->expectedEvents & evList[i].events) {
  917.                 if (!conn->blocked) {
  918.                     conn->callback(conn);
  919.                 }
  920.             } else if (conn->fd == sfd) {
  921.                 FPRINTF("listening socket: unexpected events\n");
  922.             } else {
  923.                 FPRINTF("unexpected events\n");
  924.                 if (conn->assocConn) {
  925.                     closeConn(conn->assocConn);
  926.                 }
  927.                 closeConn(conn);
  928.             }
  929.         }
  930.     }
  931. }
  932.  
  933. int main(int argc, char **argv)
  934. {
  935.     char c;
  936.     char *port = "1080"; //set port here
  937.     int daemonize = 1;
  938.  
  939.     // options
  940.     opterr = 0;
  941.     username = "username"; //set username here
  942.     int len = strlen(username);
  943.     if (len > 200) {
  944.         printf("username too long\n");
  945.         exit(1);
  946.     }
  947.     usernameLen = len;
  948.     password = "password"; // set pass here
  949.     int len = strlen(password);
  950.     if (len > 200) {
  951.         printf("password too long\n");
  952.         exit(1);
  953.     }
  954.     passwordLen = len;
  955.     daemonize = 0;
  956.     // socket bind
  957.     struct addrinfo hints;
  958.     struct addrinfo *result, *rp;
  959.     int err, sfd;
  960.     memset(&hints, 0, sizeof(hints));
  961.     hints.ai_family   = AF_INET;
  962.     hints.ai_socktype = SOCK_STREAM;
  963.     hints.ai_flags    = AI_PASSIVE | AI_NUMERICSERV;
  964.     err = getaddrinfo(NULL, port, &hints, &result);
  965.     if (err != 0) {
  966.         printf("getaddrinfo error: %s\n", gai_strerror(err));
  967.         exit(1);
  968.     }
  969.     for (rp = result; rp != NULL; rp = rp->ai_next) {
  970.         sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  971.         if (sfd == -1) {
  972.             continue;
  973.         }
  974.         int optval = 1;
  975.         if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) {
  976.             perror("setsockopt");
  977.             exit(1);
  978.         }
  979.         if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0) {
  980.             break;
  981.         }
  982.         close(sfd);
  983.     }
  984.     if (rp == NULL) {
  985.         printf("cannot bind\n");
  986.         exit(1);
  987.     }
  988.     freeaddrinfo(result);
  989.     // listen
  990.     if (listen(sfd, 512) == -1) {
  991.         perror("listen");
  992.         exit(1);
  993.     }
  994.     // epoll
  995.     epfd = epoll_create(1);
  996.     if (epfd == -1) {
  997.         perror("epoll_create");
  998.         exit(1);
  999.     }
  1000.     // signal
  1001.     signal(SIGINT, signal_handler);
  1002.     signal(SIGTERM, signal_handler);
  1003.     signal(SIGPIPE, SIG_IGN);
  1004.     // daemon
  1005.     if (daemonize) {
  1006.         if ((logFile = fopen("my-socks5.log", "a")) == NULL) {
  1007.             perror("fopen");
  1008.             exit(1);
  1009.         }
  1010.         if (daemon(1, 0) == -1) {
  1011.             perror("daemon");
  1012.             exit(1);
  1013.         }
  1014.     } else {
  1015.         logFile = stdout;
  1016.     }
  1017.     // start
  1018.     FPRINTF("start, port = %s, pid = %d\n", port, getpid());
  1019.     FPRINTF("username: %s\n", username);
  1020.     FPRINTF("password: %s\n", password);
  1021.     start(sfd);
  1022.  
  1023.     return 0;
  1024. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement