1 ;;; socks.el --- A Socks v5 Client for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1996-2000, 2002, 2007-2018 Free Software Foundation,
6 ;; Author: William M. Perry <wmperry@gnu.org>
7 ;; Dave Love <fx@gnu.org>
8 ;; Keywords: comm, firewalls
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;; This is an implementation of the SOCKS v5 protocol as defined in
31 ;; - Finish the redirection rules stuff
32 ;; - Implement composition of servers. Recursively evaluate the
33 ;; redirection rules and do SOCKS-over-HTTP and SOCKS-in-SOCKS
37 (eval-when-compile (require 'cl-lib
))
39 ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
41 ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
44 ;; (require 'wid-edit))
46 ;; (define-widget 'dynamic-choice 'menu-choice
47 ;; "A pretty simple dynamic dropdown list"
48 ;; :format "%[%t%]: %v"
51 ;; :void '(item :format "invalid (%t)\n")
52 ;; :value-create 's5-widget-value-create
53 ;; :value-delete 'widget-children-value-delete
54 ;; :value-get 'widget-choice-value-get
55 ;; :value-inline 'widget-choice-value-inline
56 ;; :mouse-down-action 'widget-choice-mouse-down-action
57 ;; :action 'widget-choice-action
58 ;; :error "Make a choice"
59 ;; :validate 'widget-choice-validate
60 ;; :match 's5-dynamic-choice-match
61 ;; :match-inline 's5-dynamic-choice-match-inline)
63 ;; (defun s5-dynamic-choice-match (widget value)
64 ;; (let ((choices (funcall (widget-get widget :choice-function)))
66 ;; (while (and choices (not found))
67 ;; (setq current (car choices)
68 ;; choices (cdr choices)
69 ;; found (widget-apply current :match value)))
72 ;; (defun s5-dynamic-choice-match-inline (widget value)
73 ;; (let ((choices (funcall (widget-get widget :choice-function)))
75 ;; (while (and choices (not found))
76 ;; (setq current (car choices)
77 ;; choices (cdr choices)
78 ;; found (widget-match-inline current value)))
81 ;; (defun s5-widget-value-create (widget)
82 ;; (let ((choices (funcall (widget-get widget :choice-function)))
83 ;; (value (widget-get widget :value)))
85 ;; (widget-put widget :value (widget-value (car choices))))
86 ;; (widget-put widget :args choices)
87 ;; (widget-choice-value-create widget)))
89 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
90 ;;; Customization support
91 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
98 ;; (defcustom socks-server-aliases nil
99 ;; "A list of server aliases for use in access control and filtering rules."
100 ;; :type '(repeat (list :format "%v"
101 ;; :value ("" "" 1080 5)
102 ;; (string :tag "Alias")
103 ;; (string :tag "Hostname/IP Address")
104 ;; (integer :tag "Port #")
105 ;; (choice :tag "SOCKS Version"
106 ;; (integer :tag "SOCKS v4" :value 4)
107 ;; (integer :tag "SOCKS v5" :value 5)))))
109 ;; (defcustom socks-network-aliases
110 ;; '(("Anywhere" (netmask "0.0.0.0" "0.0.0.0")))
111 ;; "A list of network aliases for use in subsequent rules."
112 ;; :type '(repeat (list :format "%v"
113 ;; :value (netmask "" "255.255.255.0")
114 ;; (string :tag "Alias")
115 ;; (radio-button-choice
117 ;; (list :tag "IP address range"
118 ;; (const :format "" :value range)
119 ;; (string :tag "From")
120 ;; (string :tag "To"))
121 ;; (list :tag "IP address/netmask"
122 ;; (const :format "" :value netmask)
123 ;; (string :tag "IP Address")
124 ;; (string :tag "Netmask"))
125 ;; (list :tag "Domain Name"
126 ;; (const :format "" :value domain)
127 ;; (string :tag "Domain name"))
128 ;; (list :tag "Unique hostname/IP address"
129 ;; (const :format "" :value exact)
130 ;; (string :tag "Hostname/IP Address"))))))
132 ;; (defun s5-servers-filter ()
133 ;; (if socks-server-aliases
134 ;; (mapcar (lambda (x) (list 'const :tag (car x) :value (car x))) s5-server-aliases)
135 ;; '((const :tag "No aliases defined" :value nil))))
137 ;; (defun s5-network-aliases-filter ()
138 ;; (mapcar (lambda (x) (list 'const :tag (car x) :value (car x)))
139 ;; socks-network-aliases))
141 ;; (defcustom socks-redirection-rules
143 ;; "A list of redirection rules."
144 ;; :type '(repeat (list :format "%v"
145 ;; :value ("Anywhere" nil)
146 ;; (dynamic-choice :choice-function s5-network-aliases-filter
147 ;; :tag "Destination network")
148 ;; (radio-button-choice
149 ;; :tag "Connection type"
150 ;; (const :tag "Direct connection" :value nil)
151 ;; (dynamic-choice :format "%t: %[%v%]"
152 ;; :choice-function s5-servers-filter
153 ;; :tag "Proxy chain via")))))
155 (defcustom socks-server
156 (list "Default server" "socks" 1080 5)
159 (string :format
"" :value
"Default server")
160 (string :tag
"Server")
161 (integer :tag
"Port")
162 (radio-button-choice :tag
"SOCKS Version"
164 (const :tag
"SOCKS v4 " :format
"%t" :value
4)
165 (const :tag
"SOCKS v5" :format
"%t" :value
5))))
168 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
169 ;;; Get down to the nitty gritty
170 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
171 (defconst socks-version
5)
172 (defvar socks-debug nil
)
174 ;; Common socks v5 commands
175 (defconst socks-connect-command
1)
176 (defconst socks-bind-command
2)
177 (defconst socks-udp-associate-command
3)
179 ;; Miscellaneous other socks constants
180 (defconst socks-authentication-null
0)
181 (defconst socks-authentication-failure
255)
184 (defconst socks-response-success
0)
185 (defconst socks-response-general-failure
1)
186 (defconst socks-response-access-denied
2)
187 (defconst socks-response-network-unreachable
3)
188 (defconst socks-response-host-unreachable
4)
189 (defconst socks-response-connection-refused
5)
190 (defconst socks-response-ttl-expired
6)
191 (defconst socks-response-cmd-not-supported
7)
192 (defconst socks-response-address-not-supported
8)
196 "General SOCKS server failure"
197 "Connection not allowed by ruleset"
198 "Network unreachable"
201 "Time-to-live expired"
202 "Command not supported"
203 "Address type not supported"))
205 ;; The socks v5 address types
206 (defconst socks-address-type-v4
1)
207 (defconst socks-address-type-name
3)
208 (defconst socks-address-type-v6
4)
211 (defvar socks-timeout
5)
213 ;; Miscellaneous stuff for authentication
214 (defvar socks-authentication-methods nil
)
215 (defvar socks-username
(user-login-name))
216 (defvar socks-password nil
)
218 (defun socks-register-authentication-method (id desc callback
)
219 (let ((old (assq id socks-authentication-methods
)))
221 (setcdr old
(cons desc callback
))
222 (setq socks-authentication-methods
223 (cons (cons id
(cons desc callback
))
224 socks-authentication-methods
)))))
226 (defun socks-unregister-authentication-method (id)
227 (let ((old (assq id socks-authentication-methods
)))
229 (setq socks-authentication-methods
230 (delq old socks-authentication-methods
)))))
232 (socks-register-authentication-method 0 "No authentication" 'identity
)
234 (defun socks-build-auth-list ()
240 (if (fboundp (cdr (cdr x
)))
241 (setq retval
(format "%s%c" retval
(car x
))
243 (reverse socks-authentication-methods
))
244 (format "%c%s" num retval
)))
246 (defconst socks-state-waiting-for-auth
0)
247 (defconst socks-state-submethod-negotiation
1)
248 (defconst socks-state-authenticated
2)
249 (defconst socks-state-waiting
3)
250 (defconst socks-state-connected
4)
252 (defun socks-wait-for-state-change (proc cur-state
)
253 (while (and (= (process-get proc
'socks-state
) cur-state
)
254 (memq (process-status proc
) '(run open
)))
255 (accept-process-output proc socks-timeout
)))
257 (defun socks-filter (proc string
)
258 (let (state version desired-len
)
259 (or (process-get proc
'socks
)
260 (error "socks-filter called on non-SOCKS connection %S" proc
))
261 (setq state
(process-get proc
'socks-state
))
263 ((= state socks-state-waiting-for-auth
)
264 (cl-callf (lambda (s) (setq string
(concat string s
)))
265 (process-get proc
'socks-scratch
))
266 (if (< (length string
) 2)
267 nil
; We need to spin some more
268 (process-put proc
'socks-authtype
(aref string
1))
269 (process-put proc
'socks-scratch
(substring string
2 nil
))
270 (process-put proc
'socks-state socks-state-submethod-negotiation
)))
271 ((= state socks-state-submethod-negotiation
)
273 ((= state socks-state-authenticated
)
275 ((= state socks-state-waiting
)
276 (cl-callf (lambda (s) (setq string
(concat string s
)))
277 (process-get proc
'socks-scratch
))
278 (setq version
(process-get proc
'socks-server-protocol
))
280 ((equal version
'http
)
281 (if (not (string-match "\r\n\r\n" string
))
282 nil
; Need to spin some more
283 (process-put proc
'socks-state socks-state-connected
)
284 (process-put proc
'socks-reply
0)
285 (process-put proc
'socks-response string
)))
287 (if (< (length string
) 2)
288 nil
; Can't know how much to read yet
290 (+ 4 ; address length
294 (if (< (length string
) desired-len
)
295 nil
; need to spin some more
296 (let ((response (aref string
1)))
299 (process-put proc
'socks-state socks-state-connected
)
300 (process-put proc
'socks-reply response
)
301 (process-put proc
'socks-response string
)))))
303 (if (< (length string
) 4)
306 (+ 6 ; Standard socks header
307 (pcase (aref string
3)
308 ((pred (= socks-address-type-v4
)) 4)
309 ((pred (= socks-address-type-v6
)) 16)
310 ((pred (= socks-address-type-name
))
311 (if (< (length string
) 5)
313 (+ 1 (aref string
4)))))))
314 (if (< (length string
) desired-len
)
315 nil
; Need to spin some more
316 (process-put proc
'socks-state socks-state-connected
)
317 (process-put proc
'socks-reply
(aref string
1))
318 (process-put proc
'socks-response string
))))))
319 ((= state socks-state-connected
)))))
321 ;; FIXME this is a terrible idea.
322 ;; It is not even compatible with the argument spec of open-network-stream
325 (defvar socks-override-functions nil
326 "If non-nil, overwrite `open-network-stream' function with SOCKSified version.")
328 (when socks-override-functions
329 (advice-add 'open-network-stream
:around
#'socks--open-network-stream
))
331 (defun socks-open-connection (server-info)
335 (let ((socks-override-functions nil
))
336 (open-network-stream "socks"
339 (nth 2 server-info
))))
343 ;; Initialize process and info about the process
344 (set-process-filter proc
#'socks-filter
)
345 (set-process-query-on-exit-flag proc nil
)
346 (process-put proc
'socks t
)
347 (process-put proc
'socks-state socks-state-waiting-for-auth
)
348 (process-put proc
'socks-authtype socks-authentication-failure
)
349 (process-put proc
'socks-server-protocol
(nth 3 server-info
))
350 (process-put proc
'socks-server-name
(nth 1 server-info
))
351 (setq version
(nth 3 server-info
))
353 ((equal version
'http
)
354 ;; Don't really have to do any connection setup under http
357 ;; Don't really have to do any connection setup under v4
360 ;; Need to handle all the authentication crap under v5
361 ;; Send what we think we can handle for authentication types
362 (process-send-string proc
(format "%c%s" socks-version
363 (socks-build-auth-list)))
365 ;; Basically just do a select() until we change states.
366 (socks-wait-for-state-change proc socks-state-waiting-for-auth
)
367 (setq authtype
(process-get proc
'socks-authtype
))
369 ((= authtype socks-authentication-null
)
370 (and socks-debug
(message "No authentication necessary")))
371 ((= authtype socks-authentication-failure
)
372 (error "No acceptable authentication methods found"))
374 (let* ((auth-type (process-get proc
'socks-authtype
))
375 (auth-handler (assoc auth-type socks-authentication-methods
))
376 (auth-func (and auth-handler
(cdr (cdr auth-handler
))))
377 (auth-desc (and auth-handler
(car (cdr auth-handler
)))))
378 (set-process-filter proc nil
)
379 (if (and auth-func
(fboundp auth-func
)
380 (funcall auth-func proc
))
382 (delete-process proc
)
383 (error "Failed to use auth method: %s (%d)"
384 (or auth-desc
"Unknown") auth-type
))
388 (process-put proc
'socks-state socks-state-authenticated
)
389 (set-process-filter proc
#'socks-filter
)))
392 (defun socks-send-command (proc command atype address port
)
394 ((or (= atype socks-address-type-v4
)
395 (= atype socks-address-type-v6
))
397 ((= atype socks-address-type-name
)
398 (format "%c%s" (length address
) address
))
400 (error "Unknown address type: %d" atype
))))
402 (or (process-get proc
'socks
)
403 (error "socks-send-command called on non-SOCKS connection %S" proc
))
404 (process-put proc
'socks-state socks-state-waiting
)
405 (setq version
(process-get proc
'socks-server-protocol
))
407 ((equal version
'http
)
408 (setq request
(format (eval-when-compile
410 "CONNECT %s:%d HTTP/1.0\r\n"
411 "User-Agent: Emacs/SOCKS v1.0\r\n"
414 ((equal atype socks-address-type-name
) address
)
416 (error "Unsupported address type for HTTP: %d" atype
)))
419 (setq request
(concat
423 (lsh port -
8) ; port, high byte
424 (logand port
#xff
)) ; port, low byte
426 (user-full-name) ; username
427 "\0"))) ; terminate username
429 (setq request
(concat
434 atype
) ; address type
437 (lsh port -
8) ; port, high byte
438 (logand port
#xff
))))) ; port, low byte
440 (error "Unknown protocol version: %d" version
)))
441 (process-send-string proc request
)
442 (socks-wait-for-state-change proc socks-state-waiting
)
443 (process-status proc
)
444 (if (= (or (process-get proc
'socks-reply
) 1) socks-response-success
)
445 nil
; Sweet sweet success!
446 (delete-process proc
)
448 (nth (or (process-get proc
'socks-reply
) 1) socks-errors
)))
452 ;; Replacement functions for open-network-stream, etc.
453 (defvar socks-noproxy nil
454 "List of regexps matching hosts that we should not socksify connections to")
456 (defun socks-find-route (host _service
)
457 (let ((route socks-server
)
458 (noproxy socks-noproxy
))
460 (if (eq ?
! (aref (car noproxy
) 0))
461 (if (string-match (substring (car noproxy
) 1) host
)
463 (if (string-match (car noproxy
) host
)
466 (setq noproxy
(cdr noproxy
)))
469 (defvar socks-services-file
"/etc/services")
470 (defvar socks-tcp-services
(make-hash-table :size
13 :test
'equal
))
471 (defvar socks-udp-services
(make-hash-table :size
13 :test
'equal
))
473 (defun socks-parse-services ()
474 (if (not (and (file-exists-p socks-services-file
)
475 (file-readable-p socks-services-file
)))
476 (error "Could not find services file: %s" socks-services-file
))
477 (clrhash socks-tcp-services
)
478 (clrhash socks-udp-services
)
479 (with-current-buffer (get-buffer-create " *socks-tmp*")
481 (insert-file-contents socks-services-file
)
483 (goto-char (point-min))
484 (while (re-search-forward "#.*" nil t
)
487 (goto-char (point-min))
488 (while (re-search-forward "^[ \t\n]+" nil t
)
490 ;; Now find all the lines
491 (goto-char (point-min))
492 (let (name port type
)
493 (while (re-search-forward "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)/\\([a-z]+\\)"
495 (setq name
(downcase (match-string 1))
496 port
(string-to-number (match-string 2))
497 type
(downcase (match-string 3)))
498 (puthash name port
(if (equal type
"udp")
500 socks-tcp-services
))))))
502 (defun socks-find-services-entry (service &optional udp
)
503 "Return the port # associated with SERVICE."
504 (if (= (hash-table-count socks-tcp-services
) 0)
505 (socks-parse-services))
506 (gethash (downcase service
)
507 (if udp socks-udp-services socks-tcp-services
)))
509 (defun socks-open-network-stream (name buffer host service
)
510 (let ((socks-override-functions t
))
511 (socks--open-network-stream
513 (let ((socks-override-functions nil
))
514 (apply #'open-network-stream args
)))
515 name buffer host service
)))
517 (defun socks--open-network-stream (orig-fun name buffer host service
&rest params
)
518 (let ((route (and socks-override-functions
519 (socks-find-route host service
))))
521 (apply orig-fun name buffer host service params
)
522 ;; FIXME: Obey `params'!
523 (let* ((proc (socks-open-connection route
))
524 (version (process-get proc
'socks-server-protocol
))
528 (setq host
(socks-nslookup-host host
))
529 (if (not (listp host
))
530 (error "Could not get IP address for: %s" host
))
531 (setq host
(apply #'format
"%c%c%c%c" host
))
532 socks-address-type-v4
)
534 socks-address-type-name
))))
535 (socks-send-command proc
536 socks-connect-command
539 (if (stringp service
)
541 (socks-find-services-entry service
)
542 (error "Unknown service: %s" service
))
544 (process-put proc
'socks-buffer buffer
)
545 (process-put proc
'socks-host host
)
546 (process-put proc
'socks-service host
)
547 (set-process-filter proc nil
)
548 (set-process-buffer proc
(if buffer
(get-buffer-create buffer
)))
551 ;; Authentication modules go here
553 ;; Basic username/password authentication, ala RFC 1929
554 (socks-register-authentication-method 2 "Username/Password"
555 'socks-username
/password-auth
)
557 (defconst socks-username
/password-auth-version
1)
559 (defun socks-username/password-auth-filter
(proc str
)
560 (or (process-get proc
'socks
)
561 (error "socks-filter called on non-SOCKS connection %S" proc
))
562 (cl-callf (lambda (s) (concat s str
))
563 (process-get proc
'socks-scratch
))
564 (if (< (length (process-get proc
'socks-scratch
)) 2)
566 (process-put proc
'socks-password-auth-status
567 (aref (process-get proc
'socks-scratch
) 1))
568 (process-put proc
'socks-state socks-state-authenticated
)))
570 (defun socks-username/password-auth
(proc)
571 (let ((state (process-get proc
'socks-state
)))
572 (if (not socks-password
)
573 (setq socks-password
(read-passwd
574 (format "Password for %s@%s: "
576 (process-get proc
'socks-server-name
)))))
577 (process-put proc
'socks-scratch
"")
578 (set-process-filter proc
#'socks-username
/password-auth-filter
)
579 (process-send-string proc
581 socks-username
/password-auth-version
582 (length socks-username
)
584 (length socks-password
)
586 (socks-wait-for-state-change proc state
)
587 (= (process-get proc
'socks-password-auth-status
) 0)))
590 ;; More advanced GSS/API stuff, not yet implemented - volunteers?
591 ;; (socks-register-authentication-method 1 "GSS/API" 'socks-gssapi-auth)
593 (defun socks-gssapi-auth (_proc)
598 ;; (socks-register-authentication-method 3 "CHAP" 'socks-chap-auth)
599 (defun socks-chap-auth (_proc)
604 ;; (socks-register-authentication-method 5 "CRAM" 'socks-cram-auth)
605 (defun socks-cram-auth (_proc)
609 (defcustom socks-nslookup-program
"nslookup"
610 "If non-nil then a string naming the nslookup program."
611 :type
'(choice (const :tag
"None" :value nil
) string
))
613 (defun socks-nslookup-host (host)
614 "Attempt to resolve the given HOSTNAME using nslookup if possible."
615 (interactive "sHost: ")
616 (if socks-nslookup-program
617 (let ((proc (start-process " *nslookup*" " *nslookup*"
618 socks-nslookup-program host
))
620 (set-process-query-on-exit-flag proc nil
)
621 (with-current-buffer (process-buffer proc
)
623 (accept-process-output proc
)
624 (memq (process-status proc
) '(run open
))))
625 (goto-char (point-min))
626 (if (re-search-forward "Name:.*\nAddress\\(es\\)?: *\\([0-9.]+\\)$" nil t
)
628 (setq res
(buffer-substring (match-beginning 2)
630 res
(mapcar #'string-to-number
631 (split-string res
"\\.")))))
632 (kill-buffer (current-buffer)))
638 ;;; socks.el ends here