1 ;;; socks.el --- A Socks v5 Client for Emacs
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2002,
4 ;; 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
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 <http://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
39 (if (not (fboundp 'split-string
))
40 (defun split-string (string &optional pattern
)
41 "Return a list of substrings of STRING which are separated by PATTERN.
42 If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
44 (setq pattern
"[ \f\t\n\r\v]+"))
45 (let (parts (start 0))
46 (while (string-match pattern string start
)
47 (setq parts
(cons (substring string start
(match-beginning 0)) parts
)
49 (nreverse (cons (substring string start
) parts
)))))
50 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
52 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
53 (define-widget 'dynamic-choice
'menu-choice
54 "A pretty simple dynamic dropdown list"
58 :void
'(item :format
"invalid (%t)\n")
59 :value-create
's5-widget-value-create
60 :value-delete
'widget-children-value-delete
61 :value-get
'widget-choice-value-get
62 :value-inline
'widget-choice-value-inline
63 :mouse-down-action
'widget-choice-mouse-down-action
64 :action
'widget-choice-action
65 :error
"Make a choice"
66 :validate
'widget-choice-validate
67 :match
's5-dynamic-choice-match
68 :match-inline
's5-dynamic-choice-match-inline
)
70 (defun s5-dynamic-choice-match (widget value
)
71 (let ((choices (funcall (widget-get widget
:choice-function
)))
73 (while (and choices
(not found
))
74 (setq current
(car choices
)
76 found
(widget-apply current
:match value
)))
79 (defun s5-dynamic-choice-match-inline (widget value
)
80 (let ((choices (funcall (widget-get widget
:choice-function
)))
82 (while (and choices
(not found
))
83 (setq current
(car choices
)
85 found
(widget-match-inline current value
)))
88 (defun s5-widget-value-create (widget)
89 (let ((choices (funcall (widget-get widget
:choice-function
)))
90 (value (widget-get widget
:value
)))
92 (widget-put widget
:value
(widget-value (car choices
))))
93 (widget-put widget
:args choices
)
94 (widget-choice-value-create widget
)))
96 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
97 ;;; Customization support
98 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
105 '(defcustom socks-server-aliases nil
106 "A list of server aliases for use in access control and filtering rules."
108 :type
'(repeat (list :format
"%v"
109 :value
("" "" 1080 5)
110 (string :tag
"Alias")
111 (string :tag
"Hostname/IP Address")
112 (integer :tag
"Port #")
113 (choice :tag
"SOCKS Version"
114 (integer :tag
"SOCKS v4" :value
4)
115 (integer :tag
"SOCKS v5" :value
5)))))
117 '(defcustom socks-network-aliases
118 '(("Anywhere" (netmask "0.0.0.0" "0.0.0.0")))
119 "A list of network aliases for use in subsequent rules."
121 :type
'(repeat (list :format
"%v"
122 :value
(netmask "" "255.255.255.0")
123 (string :tag
"Alias")
126 (list :tag
"IP address range"
127 (const :format
"" :value range
)
130 (list :tag
"IP address/netmask"
131 (const :format
"" :value netmask
)
132 (string :tag
"IP Address")
133 (string :tag
"Netmask"))
134 (list :tag
"Domain Name"
135 (const :format
"" :value domain
)
136 (string :tag
"Domain name"))
137 (list :tag
"Unique hostname/IP address"
138 (const :format
"" :value exact
)
139 (string :tag
"Hostname/IP Address"))))))
141 '(defun s5-servers-filter ()
142 (if socks-server-aliases
143 (mapcar (lambda (x) (list 'const
:tag
(car x
) :value
(car x
))) s5-server-aliases
)
144 '((const :tag
"No aliases defined" :value nil
))))
146 '(defun s5-network-aliases-filter ()
147 (mapcar (lambda (x) (list 'const
:tag
(car x
) :value
(car x
)))
148 socks-network-aliases
))
150 '(defcustom socks-redirection-rules
152 "A list of redirection rules."
154 :type
'(repeat (list :format
"%v"
155 :value
("Anywhere" nil
)
156 (dynamic-choice :choice-function s5-network-aliases-filter
157 :tag
"Destination network")
159 :tag
"Connection type"
160 (const :tag
"Direct connection" :value nil
)
161 (dynamic-choice :format
"%t: %[%v%]"
162 :choice-function s5-servers-filter
163 :tag
"Proxy chain via")))))
165 (defcustom socks-server
166 (list "Default server" "socks" 1080 5)
170 (string :format
"" :value
"Default server")
171 (string :tag
"Server")
172 (integer :tag
"Port")
173 (radio-button-choice :tag
"SOCKS Version"
175 (const :tag
"SOCKS v4 " :format
"%t" :value
4)
176 (const :tag
"SOCKS v5" :format
"%t" :value
5))))
179 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
180 ;;; Get down to the nitty gritty
181 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
182 (defconst socks-version
5)
183 (defvar socks-debug nil
)
185 ;; Common socks v5 commands
186 (defconst socks-connect-command
1)
187 (defconst socks-bind-command
2)
188 (defconst socks-udp-associate-command
3)
190 ;; Miscellaneous other socks constants
191 (defconst socks-authentication-null
0)
192 (defconst socks-authentication-failure
255)
195 (defconst socks-response-success
0)
196 (defconst socks-response-general-failure
1)
197 (defconst socks-response-access-denied
2)
198 (defconst socks-response-network-unreachable
3)
199 (defconst socks-response-host-unreachable
4)
200 (defconst socks-response-connection-refused
5)
201 (defconst socks-response-ttl-expired
6)
202 (defconst socks-response-cmd-not-supported
7)
203 (defconst socks-response-address-not-supported
8)
207 "General SOCKS server failure"
208 "Connection not allowed by ruleset"
209 "Network unreachable"
212 "Time-to-live expired"
213 "Command not supported"
214 "Address type not supported"))
216 ;; The socks v5 address types
217 (defconst socks-address-type-v4
1)
218 (defconst socks-address-type-name
3)
219 (defconst socks-address-type-v6
4)
222 (defvar socks-timeout
5)
223 (defvar socks-connections
(make-hash-table :size
13))
225 ;; Miscellaneous stuff for authentication
226 (defvar socks-authentication-methods nil
)
227 (defvar socks-username
(user-login-name))
228 (defvar socks-password nil
)
230 (defun socks-register-authentication-method (id desc callback
)
231 (let ((old (assq id socks-authentication-methods
)))
233 (setcdr old
(cons desc callback
))
234 (setq socks-authentication-methods
235 (cons (cons id
(cons desc callback
))
236 socks-authentication-methods
)))))
238 (defun socks-unregister-authentication-method (id)
239 (let ((old (assq id socks-authentication-methods
)))
241 (setq socks-authentication-methods
242 (delq old socks-authentication-methods
)))))
244 (socks-register-authentication-method 0 "No authentication" 'identity
)
246 (defun socks-build-auth-list ()
252 (if (fboundp (cdr (cdr x
)))
253 (setq retval
(format "%s%c" retval
(car x
))
255 (reverse socks-authentication-methods
))
256 (format "%c%s" num retval
)))
258 (defconst socks-state-waiting-for-auth
0)
259 (defconst socks-state-submethod-negotiation
1)
260 (defconst socks-state-authenticated
2)
261 (defconst socks-state-waiting
3)
262 (defconst socks-state-connected
4)
264 (defmacro socks-wait-for-state-change
(proc htable cur-state
)
265 `(while (and (= (gethash 'state
,htable
) ,cur-state
)
266 (memq (process-status ,proc
) '(run open
)))
267 (accept-process-output ,proc socks-timeout
)))
269 (defun socks-filter (proc string
)
270 (let ((info (gethash proc socks-connections
))
271 state version desired-len
)
272 (or info
(error "socks-filter called on non-SOCKS connection %S" proc
))
273 (setq state
(gethash 'state info
))
275 ((= state socks-state-waiting-for-auth
)
276 (puthash 'scratch
(concat string
(gethash 'scratch info
)) info
)
277 (setq string
(gethash 'scratch info
))
278 (if (< (length string
) 2)
279 nil
; We need to spin some more
280 (puthash 'authtype
(aref string
1) info
)
281 (puthash 'scratch
(substring string
2 nil
) info
)
282 (puthash 'state socks-state-submethod-negotiation info
)))
283 ((= state socks-state-submethod-negotiation
)
285 ((= state socks-state-authenticated
)
287 ((= state socks-state-waiting
)
288 (puthash 'scratch
(concat string
(gethash 'scratch info
)) info
)
289 (setq string
(gethash 'scratch info
))
290 (setq version
(gethash 'server-protocol info
))
292 ((equal version
'http
)
293 (if (not (string-match "\r\n\r\n" string
))
294 nil
; Need to spin some more
295 (puthash 'state socks-state-connected info
)
296 (puthash 'reply
0 info
)
297 (puthash 'response string info
)))
299 (if (< (length string
) 2)
300 nil
; Can't know how much to read yet
302 (+ 4 ; address length
306 (if (< (length string
) desired-len
)
307 nil
; need to spin some more
308 (let ((response (aref string
1)))
311 (puthash 'state socks-state-connected info
)
312 (puthash 'reply response info
)
313 (puthash 'response string info
)))))
315 (if (< (length string
) 4)
318 (+ 6 ; Standard socks header
320 ((= (aref string
3) socks-address-type-v4
) 4)
321 ((= (aref string
3) socks-address-type-v6
) 16)
322 ((= (aref string
3) socks-address-type-name
)
323 (if (< (length string
) 5)
325 (+ 1 (aref string
4)))))))
326 (if (< (length string
) desired-len
)
327 nil
; Need to spin some more
328 (puthash 'state socks-state-connected info
)
329 (puthash 'reply
(aref string
1) info
)
330 (puthash 'response string info
))))))
331 ((= state socks-state-connected
)
337 (declare-function socks-original-open-network-stream
"socks") ; fset
339 (defvar socks-override-functions nil
340 "*Whether to overwrite the open-network-stream function with the SOCKSified
343 (if (fboundp 'socks-original-open-network-stream
)
344 nil
; Do nothing, we've been here already
345 (defalias 'socks-original-open-network-stream
346 (symbol-function 'open-network-stream
))
347 (if socks-override-functions
348 (defalias 'open-network-stream
'socks-open-network-stream
)))
350 (defun socks-open-connection (server-info)
353 (let ((proc (socks-original-open-network-stream "socks"
356 (nth 2 server-info
)))
357 (info (make-hash-table :size
13))
361 ;; Initialize process and info about the process
362 (set-process-filter proc
'socks-filter
)
363 (set-process-query-on-exit-flag proc nil
)
364 (puthash proc info socks-connections
)
365 (puthash 'state socks-state-waiting-for-auth info
)
366 (puthash 'authtype socks-authentication-failure info
)
367 (puthash 'server-protocol
(nth 3 server-info
) info
)
368 (puthash 'server-name
(nth 1 server-info
) info
)
369 (setq version
(nth 3 server-info
))
371 ((equal version
'http
)
372 ;; Don't really have to do any connection setup under http
375 ;; Don't really have to do any connection setup under v4
378 ;; Need to handle all the authentication crap under v5
379 ;; Send what we think we can handle for authentication types
380 (process-send-string proc
(format "%c%s" socks-version
381 (socks-build-auth-list)))
383 ;; Basically just do a select() until we change states.
384 (socks-wait-for-state-change proc info socks-state-waiting-for-auth
)
385 (setq authtype
(gethash 'authtype info
))
387 ((= authtype socks-authentication-null
)
388 (and socks-debug
(message "No authentication necessary")))
389 ((= authtype socks-authentication-failure
)
390 (error "No acceptable authentication methods found"))
392 (let* ((auth-type (gethash 'authtype info
))
393 (auth-handler (assoc auth-type socks-authentication-methods
))
394 (auth-func (and auth-handler
(cdr (cdr auth-handler
))))
395 (auth-desc (and auth-handler
(car (cdr auth-handler
)))))
396 (set-process-filter proc nil
)
397 (if (and auth-func
(fboundp auth-func
)
398 (funcall auth-func proc
))
400 (delete-process proc
)
401 (error "Failed to use auth method: %s (%d)"
402 (or auth-desc
"Unknown") auth-type
))
406 (puthash 'state socks-state-authenticated info
)
407 (set-process-filter proc
'socks-filter
)))
410 (defun socks-send-command (proc command atype address port
)
412 ((or (= atype socks-address-type-v4
)
413 (= atype socks-address-type-v6
))
415 ((= atype socks-address-type-name
)
416 (format "%c%s" (length address
) address
))
418 (error "Unkown address type: %d" atype
))))
419 (info (gethash proc socks-connections
))
421 (or info
(error "socks-send-command called on non-SOCKS connection %S"
423 (puthash 'state socks-state-waiting info
)
424 (setq version
(gethash 'server-protocol info
))
426 ((equal version
'http
)
427 (setq request
(format (eval-when-compile
429 "CONNECT %s:%d HTTP/1.0\r\n"
430 "User-Agent: Emacs/SOCKS v1.0\r\n"
433 ((equal atype socks-address-type-name
) address
)
435 (error "Unsupported address type for HTTP: %d" atype
)))
438 (setq request
(string-make-unibyte
443 (lsh port -
8) ; port, high byte
444 (- port
(lsh (lsh port -
8) 8)) ; port, low byte
446 (user-full-name) ; username
447 0 ; terminate username
450 (setq request
(string-make-unibyte
458 (lsh port -
8) ; port, high byte
459 (- port
(lsh (lsh port -
8) 8)) ; port, low byte
462 (error "Unknown protocol version: %d" version
)))
463 (process-send-string proc request
)
464 (socks-wait-for-state-change proc info socks-state-waiting
)
465 (process-status proc
)
466 (if (= (or (gethash 'reply info
) 1) socks-response-success
)
467 nil
; Sweet sweet success!
468 (delete-process proc
)
469 (error "SOCKS: %s" (nth (or (gethash 'reply info
) 1) socks-errors
)))
473 ;; Replacement functions for open-network-stream, etc.
474 (defvar socks-noproxy nil
475 "*List of regexps matching hosts that we should not socksify connections to")
477 (defun socks-find-route (host service
)
478 (let ((route socks-server
)
479 (noproxy socks-noproxy
))
481 (if (eq ?
! (aref (car noproxy
) 0))
482 (if (string-match (substring (car noproxy
) 1) host
)
484 (if (string-match (car noproxy
) host
)
487 (setq noproxy
(cdr noproxy
)))
490 (defvar socks-services-file
"/etc/services")
491 (defvar socks-tcp-services
(make-hash-table :size
13 :test
'equal
))
492 (defvar socks-udp-services
(make-hash-table :size
13 :test
'equal
))
494 (defun socks-parse-services ()
495 (if (not (and (file-exists-p socks-services-file
)
496 (file-readable-p socks-services-file
)))
497 (error "Could not find services file: %s" socks-services-file
))
498 (clrhash socks-tcp-services
)
499 (clrhash socks-udp-services
)
500 (with-current-buffer (get-buffer-create " *socks-tmp*")
502 (insert-file-contents socks-services-file
)
504 (goto-char (point-min))
505 (while (re-search-forward "#.*" nil t
)
508 (goto-char (point-min))
509 (while (re-search-forward "^[ \t\n]+" nil t
)
511 ;; Now find all the lines
512 (goto-char (point-min))
513 (let (name port type
)
514 (while (re-search-forward "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)/\\([a-z]+\\)"
516 (setq name
(downcase (match-string 1))
517 port
(string-to-number (match-string 2))
518 type
(downcase (match-string 3)))
519 (puthash name port
(if (equal type
"udp")
521 socks-tcp-services
))))))
523 (defun socks-find-services-entry (service &optional udp
)
524 "Return the port # associated with SERVICE"
525 (if (= (hash-table-count socks-tcp-services
) 0)
526 (socks-parse-services))
527 (gethash (downcase service
)
528 (if udp socks-udp-services socks-tcp-services
)))
530 (defun socks-open-network-stream (name buffer host service
)
531 (let* ((route (socks-find-route host service
))
532 proc info version atype
)
534 (socks-original-open-network-stream name buffer host service
)
535 (setq proc
(socks-open-connection route
)
536 info
(gethash proc socks-connections
)
537 version
(gethash 'server-protocol info
))
540 (setq host
(socks-nslookup-host host
))
541 (if (not (listp host
))
542 (error "Could not get IP address for: %s" host
))
543 (setq host
(apply 'format
"%c%c%c%c" host
))
544 (setq atype socks-address-type-v4
))
546 (setq atype socks-address-type-name
)))
547 (socks-send-command proc
548 socks-connect-command
551 (if (stringp service
)
553 (socks-find-services-entry service
)
554 (error "Unknown service: %s" service
))
556 (puthash 'buffer buffer info
)
557 (puthash 'host host info
)
558 (puthash 'service host info
)
559 (set-process-filter proc nil
)
560 (set-process-buffer proc
(if buffer
(get-buffer-create buffer
)))
563 ;; Authentication modules go here
565 ;; Basic username/password authentication, ala RFC 1929
566 (socks-register-authentication-method 2 "Username/Password"
567 'socks-username
/password-auth
)
569 (defconst socks-username
/password-auth-version
1)
571 (defun socks-username/password-auth-filter
(proc str
)
572 (let ((info (gethash proc socks-connections
)))
573 (or info
(error "socks-filter called on non-SOCKS connection %S" proc
))
574 (puthash 'scratch
(concat (gethash 'scratch info
) str
) info
)
575 (if (< (length (gethash 'scratch info
)) 2)
577 (puthash 'password-auth-status
(aref (gethash 'scratch info
) 1) info
)
578 (puthash 'state socks-state-authenticated info
))))
580 (defun socks-username/password-auth
(proc)
581 (let* ((info (gethash proc socks-connections
))
582 (state (gethash 'state info
)))
583 (if (not socks-password
)
584 (setq socks-password
(read-passwd
585 (format "Password for %s@%s: "
587 (gethash 'server-name info
)))))
588 (puthash 'scratch
"" info
)
589 (set-process-filter proc
'socks-username
/password-auth-filter
)
590 (process-send-string proc
592 socks-username
/password-auth-version
593 (length socks-username
)
595 (length socks-password
)
597 (socks-wait-for-state-change proc info state
)
598 (= (gethash 'password-auth-status info
) 0)))
601 ;; More advanced GSS/API stuff, not yet implemented - volunteers?
602 ;; (socks-register-authentication-method 1 "GSS/API" 'socks-gssapi-auth)
604 (defun socks-gssapi-auth (proc)
609 ;; (socks-register-authentication-method 3 "CHAP" 'socks-chap-auth)
610 (defun socks-chap-auth (proc)
615 ;; (socks-register-authentication-method 5 "CRAM" 'socks-cram-auth)
616 (defun socks-cram-auth (proc)
620 (defcustom socks-nslookup-program
"nslookup"
621 "*If non-NIL then a string naming the nslookup program."
622 :type
'(choice (const :tag
"None" :value nil
) string
)
625 (defun socks-nslookup-host (host)
626 "Attempt to resolve the given HOSTNAME using nslookup if possible."
627 (interactive "sHost: ")
628 (if socks-nslookup-program
629 (let ((proc (start-process " *nslookup*" " *nslookup*"
630 socks-nslookup-program host
))
632 (set-process-query-on-exit-flag proc nil
)
633 (with-current-buffer (process-buffer proc
)
635 (accept-process-output proc
)
636 (memq (process-status proc
) '(run open
))))
637 (goto-char (point-min))
638 (if (re-search-forward "Name:.*\nAddress\\(es\\)?: *\\([0-9.]+\\)$" nil t
)
640 (setq res
(buffer-substring (match-beginning 2)
642 res
(mapcar 'string-to-int
(split-string res
"\\.")))))
643 (kill-buffer (current-buffer)))
649 ;; arch-tag: 67aef0d9-f4f7-4056-89c3-b4c9bf93ce7f
650 ;;; socks.el ends here