File: socks.el

package info (click to toggle)
xemacs20 20.4-13
  • links: PTS
  • area: main
  • in suites: slink
  • size: 67,324 kB
  • ctags: 57,643
  • sloc: lisp: 586,197; ansic: 184,662; sh: 4,296; asm: 3,179; makefile: 2,021; perl: 1,059; csh: 96; sed: 22
file content (390 lines) | stat: -rw-r--r-- 13,505 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
;;; socks.el --- A Socks v5 Client for Emacs
;; Author: wmperry
;; Created: 1997/12/24 16:47:40
;; Version: 1.7
;; Keywords: comm, firewalls

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1996, 1997 by William M. Perry <wmperry@cs.indiana.edu>
;;;
;;; This file is not part of GNU Emacs, but the same permissions apply.
;;;
;;; GNU Emacs is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 2, or (at your option)
;;; any later version.
;;;
;;; GNU Emacs is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Emacs; see the file COPYING.  If not, write to
;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; This is an implementation of the SOCKS v5 protocol as defined in
;;; RFC 1928.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'cl)

(defconst socks-version 5)
(defvar socks-debug nil)

;; Common socks v5 commands
(defconst socks-connect-command 1)
(defconst socks-bind-command 2)
(defconst socks-udp-associate-command 3)

;; Miscellaneous other socks constants
(defconst socks-authentication-null 0)
(defconst socks-authentication-failure 255)

;; Response codes
(defconst socks-response-success               0)
(defconst socks-response-general-failure       1)
(defconst socks-response-access-denied         2)
(defconst socks-response-network-unreachable   3)
(defconst socks-response-host-unreachable      4)
(defconst socks-response-connection-refused    5)
(defconst socks-response-ttl-expired           6)
(defconst socks-response-cmd-not-supported     7)
(defconst socks-response-address-not-supported 8)

(defvar socks-errors
  '("Succeeded"
    "General SOCKS server failure"
    "Connection not allowed by ruleset"
    "Network unreachable"
    "Host unreachable"
    "Connection refused"
    "Time-to-live expired"
    "Command not supported"
    "Address type not supported"))

;; The socks v5 address types
(defconst socks-address-type-v4   1)
(defconst socks-address-type-name 3)
(defconst socks-address-type-v6   4)

;; Base variables
(defvar socks-host (or (getenv "SOCKS5_SERVER") "socks"))
(defvar socks-port (or (getenv "SOCKS5_PORT")   1080))
(defvar socks-timeout 5)
(defvar socks-connections (make-hash-table :size 13))

;; Miscellaneous stuff for authentication
(defvar socks-authentication-methods nil)
(defvar socks-username (user-login-name))
(defvar socks-password nil)

(defun socks-register-authentication-method (id desc callback)
  (let ((old (assq id socks-authentication-methods)))
    (if old
	(setcdr old (cons desc callback))
      (setq socks-authentication-methods
	    (cons (cons id (cons desc callback))
		  socks-authentication-methods)))))

(defun socks-unregister-authentication-method (id)
  (let ((old (assq id socks-authentication-methods)))
    (if old
	(setq socks-authentication-methods
	      (delq old socks-authentication-methods)))))

(socks-register-authentication-method 0 "No authentication" 'identity)

(defun socks-build-auth-list ()
  (let ((num 0)
	(retval ""))
    (mapcar
     (function
      (lambda (x)
	(if (fboundp (cdr (cdr x)))
	    (setq retval (format "%s%c" retval (car x))
		  num (1+ num)))))
     socks-authentication-methods)
    (format "%c%s" num retval)))

(defconst socks-state-waiting-for-auth 0)
(defconst socks-state-submethod-negotiation 1)
(defconst socks-state-authenticated 2)
(defconst socks-state-waiting 3)
(defconst socks-state-connected 4)

(defmacro socks-wait-for-state-change (proc htable cur-state)
  (`
   (while (and (= (cl-gethash 'state (, htable)) (, cur-state))
	       (memq (process-status (, proc)) '(run open)))
     (accept-process-output (, proc) socks-timeout))))

(defun socks-filter (proc string)
  (let ((info (cl-gethash proc socks-connections))
	state desired-len)
    (or info (error "socks-filter called on non-SOCKS connection %S" proc))
    (setq state (cl-gethash 'state info))
    (cond
     ((= state socks-state-waiting-for-auth)
      (cl-puthash 'scratch (concat string (cl-gethash 'scratch info)) info)
      (setq string (cl-gethash 'scratch info))
      (if (< (length string) 2)
	  nil				; We need to spin some more
	(cl-puthash 'authtype (aref string 1) info)
	(cl-puthash 'scratch (substring string 2 nil) info)
	(cl-puthash 'state socks-state-submethod-negotiation info)))
     ((= state socks-state-submethod-negotiation)
      )
     ((= state socks-state-authenticated)
      )
     ((= state socks-state-waiting)
      (cl-puthash 'scratch (concat string (cl-gethash 'scratch info)) info)
      (setq string (cl-gethash 'scratch info))
      (if (< (length string) 4)
	  nil
	(setq desired-len
	      (+ 6			; Standard socks header
		 (cond
		  ((= (aref string 3) socks-address-type-v4) 4)
		  ((= (aref string 3) socks-address-type-v6) 16)
		  ((= (aref string 3) socks-address-type-name)
		   (if (< (length string) 5)
		       255
		     (+ 1 (aref string 4)))))))
	(if (< (length string) desired-len)
	    nil				; Need to spin some more
	  (cl-puthash 'state socks-state-connected info)
	  (cl-puthash 'reply (aref string 1) info)
	  (cl-puthash 'response string info))))
     ((= state socks-state-connected)
      )
     )
    )
  )

(defun socks-open-connection (&optional host port)
  (interactive)
  (setq host (or host socks-host)
	port (or port socks-port))
  (save-excursion
    (let ((proc (socks-original-open-network-stream "socks"
						    nil
						    host port))
	  (info (make-hash-table :size 13))
	  (authtype nil))

      ;; Initialize process and info about the process
      (set-process-filter proc 'socks-filter)
      (process-kill-without-query proc)
      (cl-puthash proc info socks-connections)
      (cl-puthash 'state socks-state-waiting-for-auth info)
      (cl-puthash 'authtype socks-authentication-failure info)

      ;; Send what we think we can handle for authentication types
      (process-send-string proc (format "%c%s" socks-version
					(socks-build-auth-list)))

      ;; Basically just do a select() until we change states.
      (socks-wait-for-state-change proc info socks-state-waiting-for-auth)
      (setq authtype (cl-gethash 'authtype info))
      (cond
       ((= authtype socks-authentication-null)
	(and socks-debug (message "No authentication necessary")))
       ((= authtype socks-authentication-failure)
	(error "No acceptable authentication methods found."))
       (t
	(let* ((auth-type (char-int (cl-gethash 'authtype info)))
	       (auth-handler (assoc auth-type socks-authentication-methods))
	       (auth-func (and auth-handler (cdr (cdr auth-handler))))
	       (auth-desc (and auth-handler (car (cdr auth-handler)))))
	  (set-process-filter proc nil)
	  (if (and auth-func (fboundp auth-func)
		   (funcall auth-func proc))
	      nil			; We succeeded!
	    (delete-process proc)
	    (error "Failed to use auth method: %s (%d)"
		   (or auth-desc "Unknown") auth-type))
	  )
	)
       )
      (cl-puthash 'state socks-state-authenticated info)
      (set-process-filter proc 'socks-filter)
      proc)))

(defun socks-send-command (proc command atype address port)
  (let ((addr (case atype
		(socks-address-type-v4 address)
		(socks-address-type-v6 address)
		(t
		 (format "%c%s" (length address) address))))
	(info (cl-gethash proc socks-connections)))
    (or info (error "socks-send-command called on non-SOCKS connection %S"
		    proc))
    (cl-puthash 'state socks-state-waiting info)
    (process-send-string proc
			 (format 
			  "%c%c%c%c%s%c%c"
			  socks-version	; version 
			  command	; command
			  0		; reserved
			  atype		; address type
			  addr		; address
			  (lsh port -8)	; port, high byte
			  (- port (lsh (lsh port -8) 8)) ; port, low byte
			  ))
    (socks-wait-for-state-change proc info socks-state-waiting)
    (if (= (cl-gethash 'reply info) socks-response-success)
	nil				; Sweet sweet success!
      (delete-process proc)
      (error "%s" (nth (cl-gethash 'reply info) socks-errors)))
    proc))


;; Replacement functions for open-network-stream, etc.
(defvar socks-noproxy nil
  "*List of regexps matching hosts that we should not socksify connections to")

(defun socks-find-route (host service)
  (let ((route (cons socks-host socks-port))
	(noproxy socks-noproxy))
    (while noproxy
      (if (eq ?! (aref (car noproxy) 0))
	  (if (string-match (substring (car noproxy) 1) host)
	      (setq route nil
		    noproxy nil))
	(if (string-match (car noproxy) host)
	    (setq route nil
		  noproxy nil)))
      (setq noproxy (cdr noproxy)))
    route))

(defvar socks-override-functions nil
  "*Whether to overwrite the open-network-stream function with the SOCKSified
version.")

(if (fboundp 'socks-original-open-network-stream)
    nil					; Do nothing, we've been here already
  (fset 'socks-original-open-network-stream
	(symbol-function 'open-network-stream))
  (if socks-override-functions
      (fset 'open-network-stream 'socks-open-network-stream)))

(defvar socks-services-file "/etc/services")
(defvar socks-tcp-services (make-hash-table :size 13 :test 'equal))
(defvar socks-udp-services (make-hash-table :size 13 :test 'equal))

(defun socks-parse-services ()
  (if (not (and (file-exists-p socks-services-file)
		(file-readable-p socks-services-file)))
      (error "Could not find services file: %s" socks-services-file))
  (save-excursion
    (clrhash socks-tcp-services)
    (clrhash socks-udp-services)
    (set-buffer (get-buffer-create " *socks-tmp*"))
    (erase-buffer)
    (insert-file-contents socks-services-file)
    ;; Nuke comments
    (goto-char (point-min))
    (while (re-search-forward "#.*" nil t)
      (replace-match ""))
    ;; Nuke empty lines
    (goto-char (point-min))
    (while (re-search-forward "^[ \t\n]+" nil t)
      (replace-match ""))
    ;; Now find all the lines
    (goto-char (point-min))
    (let (name port type)
      (while (re-search-forward "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)/\\([a-z]+\\)"
				nil t)
	(setq name (downcase (match-string 1))
	      port (string-to-int (match-string 2))
	      type (downcase (match-string 3)))
	(cl-puthash name port (if (equal type "udp")
			       socks-udp-services
			     socks-tcp-services))))))

(defun socks-find-services-entry (service &optional udp)
  "Return the port # associated with SERVICE"
  (if (= (hash-table-count socks-tcp-services) 0)
      (socks-parse-services))
  (cl-gethash (downcase service)
	      (if udp socks-udp-services socks-tcp-services)))

(defun socks-open-network-stream (name buffer host service)
  (let* ((route (socks-find-route host service))
	 proc info)
    (if (not route)
	(socks-original-open-network-stream name buffer host service)
      (setq proc (socks-open-connection (car route) (cdr route))
	    info (cl-gethash proc socks-connections))
      (socks-send-command proc socks-connect-command
			  socks-address-type-name
			  host
			  (if (stringp service)
			      (socks-find-services-entry service)
			    service))
      (cl-puthash 'buffer buffer info)
      (cl-puthash 'host host info)
      (cl-puthash 'service host info)
      (set-process-filter proc nil)
      (set-process-buffer proc (if buffer (get-buffer-create buffer)))
      proc)))

;; Authentication modules go here

;; Basic username/password authentication, ala RFC 1929
(socks-register-authentication-method 2 "Username/Password"
				      'socks-username/password-auth)

(defconst socks-username/password-auth-version 1)

(if (not (fboundp 'char-int))
    (fset 'char-int 'identity))

(defun socks-username/password-auth-filter (proc str)
  (let ((info (cl-gethash proc socks-connections))
	state desired-len)
    (or info (error "socks-filter called on non-SOCKS connection %S" proc))
    (setq state (cl-gethash 'state info))
    (cl-puthash 'scratch (concat (cl-gethash 'scratch info) str) info)
    (if (< (length (cl-gethash 'scratch info)) 2)
	nil
      (cl-puthash 'password-auth-status (char-int
					 (aref (cl-gethash 'scratch info) 1))
		  info)
      (cl-puthash 'state socks-state-authenticated info))))

(defun socks-username/password-auth (proc)
  (if (not socks-password)
      (setq socks-password (read-passwd
			    (format "Password for %s@%s: "
				    socks-username socks-host))))
  (let* ((info (cl-gethash proc socks-connections))
	 (state (cl-gethash 'state info)))
    (cl-puthash 'scratch "" info)
    (set-process-filter proc 'socks-username/password-auth-filter)
    (process-send-string proc
			 (format "%c%c%s%c%s"
				 socks-username/password-auth-version
				 (length socks-username)
				 socks-username
				 (length socks-password)
				 socks-password))
    (socks-wait-for-state-change proc info state)
    (= (cl-gethash 'password-auth-status info) 0)))


;; More advanced GSS/API stuff, not yet implemented - volunteers?
;; (socks-register-authentication-method 1 "GSS/API" 'socks-gssapi-auth)

(defun socks-gssapi-auth (proc)
  nil)


;; CHAP stuff
;; (socks-register-authentication-method 3 "CHAP" 'socks-chap-auth)
(defun socks-chap-auth (proc)
  nil)

(provide 'socks)