Commit | Line | Data |
---|---|---|
a2916c06 MW |
1 | #! /usr/bin/python |
2 | ### | |
3 | ### Password management | |
4 | ### | |
5 | ### (c) 2012 Mark Wooding | |
6 | ### | |
7 | ||
8 | ###----- Licensing notice --------------------------------------------------- | |
9 | ### | |
10 | ### This file is part of Chopwood: a password-changing service. | |
11 | ### | |
12 | ### Chopwood is free software; you can redistribute it and/or modify | |
13 | ### it under the terms of the GNU Affero General Public License as | |
14 | ### published by the Free Software Foundation; either version 3 of the | |
15 | ### License, or (at your option) any later version. | |
16 | ### | |
17 | ### Chopwood 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 Affero General Public License for more details. | |
21 | ### | |
22 | ### You should have received a copy of the GNU Affero General Public | |
23 | ### License along with Chopwood; if not, see | |
24 | ### <http://www.gnu.org/licenses/>. | |
25 | ||
26 | from __future__ import with_statement | |
27 | ||
28 | import contextlib as CTX | |
29 | import optparse as OP | |
30 | import os as OS; ENV = OS.environ | |
31 | import shlex as SL | |
32 | import sys as SYS | |
710c89c8 | 33 | import syslog as L |
a2916c06 MW |
34 | |
35 | from auto import HOME, VERSION | |
36 | import cgi as CGI | |
37 | import cmdutil as CU | |
38 | import config as CONF; CFG = CONF.CFG | |
39 | import dbmaint as D | |
40 | import httpauth as HA | |
41 | import output as O; OUT = O.OUT | |
71d74dcf | 42 | import service as S |
a2916c06 MW |
43 | import subcommand as SC |
44 | import util as U | |
45 | ||
46 | for i in ['admin', 'cgi', 'remote', 'user']: | |
47 | __import__('cmd-' + i) | |
48 | ||
49 | ###-------------------------------------------------------------------------- | |
50 | ### Parsing command-line options. | |
51 | ||
52 | ## Command-line options parser. | |
53 | OPTPARSE = SC.SubcommandOptionParser( | |
54 | usage = '%prog SUBCOMMAND [ARGS ...]', | |
55 | version = '%%prog, verion %s' % VERSION, | |
56 | contexts = ['admin', 'userv', 'remote', 'cgi', 'cgi-query', 'cgi-noauth'], | |
57 | commands = SC.COMMANDS, | |
58 | description = """\ | |
59 | Manage all of those annoying passwords. | |
60 | ||
61 | This is free software, and you can redistribute it and/or modify it | |
62 | under the terms of the GNU Affero General Public License | |
63 | <http://www.gnu.org/licenses/agpl-3.0.html>. For a `.tar.gz' file | |
64 | of the source code, use the `source' command. | |
65 | """) | |
66 | ||
67 | OPTS = None | |
68 | ||
69 | ## Set up the global options. | |
70 | for short, long, props in [ | |
71 | ('-c', '--context', { | |
72 | 'metavar': 'CONTEXT', 'dest': 'context', 'default': None, | |
73 | 'help': 'run commands with the given CONTEXT' }), | |
74 | ('-f', '--config-file', { | |
75 | 'metavar': 'FILE', 'dest': 'config', | |
2a875c57 MW |
76 | 'default': ENV.get('CHPWD_CONFIG', |
77 | OS.path.join(HOME, 'chpwd.conf')), | |
a2916c06 | 78 | 'help': 'read configuration from FILE.' }), |
bb623e8f MW |
79 | ('-s', '--ssl', { |
80 | 'dest': 'sslp', 'action': 'store_true', | |
81 | 'help': 'pretend CGI connection is carried over SSL/TLS' }), | |
a2916c06 MW |
82 | ('-u', '--user', { |
83 | 'metavar': 'USER', 'dest': 'user', 'default': None, | |
84 | 'help': "impersonate USER, and default context to `userv'." })]: | |
85 | OPTPARSE.add_option(short, long, **props) | |
86 | ||
87 | ###-------------------------------------------------------------------------- | |
88 | ### CGI dispatch. | |
89 | ||
90 | ## The special variables, to be picked out by `cgiparse'. | |
91 | CGI.SPECIAL['%act'] = None | |
92 | CGI.SPECIAL['%nonce'] = None | |
ba8f1b92 | 93 | CGI.SPECIAL['%user'] = None |
a2916c06 MW |
94 | |
95 | ## We don't want to parse arguments until we've settled on a context; but | |
96 | ## issuing redirects in the early setup phase fails because we don't know | |
97 | ## the script name. So package the setup here. | |
98 | def cgi_setup(ctx = 'cgi-noauth'): | |
99 | global OPTS | |
100 | if OPTS: return | |
101 | OPTPARSE.context = ctx | |
102 | OPTS, args = OPTPARSE.parse_args() | |
103 | if args: raise U.ExpectedError, (500, 'Unexpected arguments to CGI') | |
104 | CONF.loadconfig(OPTS.config) | |
105 | D.opendb() | |
106 | ||
107 | def dispatch_cgi(): | |
108 | """Examine the CGI request and invoke the appropriate command.""" | |
109 | ||
110 | ## Start by picking apart the request. | |
111 | CGI.cgiparse() | |
112 | ||
113 | ## We'll be taking items off the trailing path. | |
114 | i, np = 0, len(CGI.PATH) | |
115 | ||
116 | ## Sometimes, we want to run several actions out of the same form, so the | |
117 | ## subcommand name needs to be in the query string. We use the special | |
118 | ## variable `%act' for this. If it's not set, then we use the first elment | |
119 | ## of the path. | |
120 | act = CGI.SPECIAL['%act'] | |
121 | if act is None: | |
122 | if i >= np: | |
123 | cgi_setup() | |
124 | CGI.redirect(CGI.action('login')) | |
125 | return | |
126 | act = CGI.PATH[i] | |
127 | i += 1 | |
128 | ||
129 | ## Figure out which context we're meant to be operating in, according to | |
130 | ## the requested action. Unknown actions result in an error here; known | |
131 | ## actions where we don't have enough authorization send the user back to | |
132 | ## the login page. | |
133 | for ctx in ['cgi-noauth', 'cgi-query', 'cgi']: | |
134 | try: | |
135 | c = OPTPARSE.lookup_subcommand(act, exactp = True, context = ctx) | |
136 | except U.ExpectedError, e: | |
137 | if e.code != 404: raise | |
138 | else: | |
139 | break | |
140 | else: | |
141 | raise e | |
142 | ||
143 | ## Parse the command line, and load configuration. | |
144 | cgi_setup(ctx) | |
145 | ||
146 | ## Check whether we have enough authorization. There's always enough for | |
147 | ## `cgi-noauth'. | |
148 | if ctx != 'cgi-noauth': | |
149 | ||
ba8f1b92 MW |
150 | ## The next part of the URL should be the user name, so that caches don't |
151 | ## cross things over. | |
152 | expuser = CGI.SPECIAL['%user'] | |
153 | if expuser is None: | |
154 | if i >= np: raise U.ExpectedError, (404, 'Missing user name') | |
155 | expuser = CGI.PATH[i] | |
156 | i += 1 | |
157 | ||
a2916c06 MW |
158 | ## If there's no token cookie, then we have to bail. |
159 | try: token = CGI.COOKIE['chpwd-token'] | |
160 | except KeyError: | |
161 | CGI.redirect(CGI.action('login', why = 'NOAUTH')) | |
162 | return | |
163 | ||
164 | ## If we only want read-only access, then the cookie is good enough. | |
165 | ## Otherwise we must check that a nonce was supplied, and that it is | |
166 | ## correct. | |
167 | if ctx == 'cgi-query': | |
168 | nonce = None | |
169 | else: | |
170 | nonce = CGI.SPECIAL['%nonce'] | |
171 | if not nonce: | |
172 | CGI.redirect(CGI.action('login', why = 'NONONCE')) | |
173 | return | |
174 | ||
175 | ## Verify the token and nonce. | |
176 | try: | |
177 | CU.USER = HA.check_auth(token, nonce) | |
178 | except HA.AuthenticationFailed, e: | |
179 | CGI.redirect(CGI.action('login', why = e.why)) | |
180 | return | |
ba8f1b92 MW |
181 | if CU.USER != expuser: raise U.ExpectedError, (401, 'User mismatch') |
182 | CGI.STATE.kw['user'] = CU.USER | |
a2916c06 MW |
183 | |
184 | ## Invoke the subcommand handler. | |
185 | c.cgi(CGI.PARAM, CGI.PATH[i:]) | |
186 | ||
187 | ###-------------------------------------------------------------------------- | |
188 | ### Main dispatch. | |
189 | ||
190 | @CTX.contextmanager | |
191 | def cli_errors(): | |
192 | """Catch expected errors and report them in the traditional Unix style.""" | |
193 | try: | |
194 | yield None | |
195 | except U.ExpectedError, e: | |
196 | SYS.stderr.write('%s: %s\n' % (OS.path.basename(SYS.argv[0]), e.msg)) | |
197 | if 400 <= e.code < 500: SYS.exit(1) | |
198 | else: SYS.exit(2) | |
199 | ||
200 | ### Main dispatch. | |
201 | ||
202 | if __name__ == '__main__': | |
203 | ||
710c89c8 MW |
204 | L.openlog(OS.path.basename(SYS.argv[0]), 0, L.LOG_AUTH) |
205 | ||
a2916c06 MW |
206 | if 'REQUEST_METHOD' in ENV: |
207 | ## This looks like a CGI request. The heavy lifting for authentication | |
208 | ## over HTTP is done in `dispatch_cgi'. | |
209 | ||
210 | with OUT.redirect_to(CGI.HTTPOutput()): | |
039df864 MW |
211 | with U.Escape() as CGI.HEADER_DONE: |
212 | with CGI.cgi_errors(cgi_setup): | |
213 | dispatch_cgi() | |
a2916c06 MW |
214 | |
215 | elif 'USERV_SERVICE' in ENV: | |
216 | ## This is a Userv request. The caller's user name is helpfully in the | |
217 | ## `USERV_USER' environment variable. | |
218 | ||
219 | with cli_errors(): | |
220 | OPTS, args = OPTPARSE.parse_args() | |
fef23140 MW |
221 | if not args or args[0] != 'userv': |
222 | raise U.ExpectedError, (500, 'missing userv token') | |
a2916c06 MW |
223 | CONF.loadconfig(OPTS.config) |
224 | try: CU.set_user(ENV['USERV_USER']) | |
225 | except KeyError: raise ExpectedError, (500, 'USERV_USER unset') | |
226 | with OUT.redirect_to(O.FileOutput()): | |
fef23140 | 227 | OPTPARSE.dispatch('userv', [ENV['USERV_SERVICE']] + args[1:]) |
a2916c06 MW |
228 | |
229 | elif 'SSH_ORIGINAL_COMMAND' in ENV: | |
230 | ## This looks like an SSH request; but we present two different | |
231 | ## interfaces over SSH. We must distinguish them -- carefully: they have | |
232 | ## very different error-reporting conventions. | |
233 | ||
234 | def ssh_setup(): | |
235 | """Extract and parse the client's request from where SSH left it.""" | |
236 | global OPTS | |
237 | OPTS, args = OPTPARSE.parse_args() | |
238 | CONF.loadconfig(OPTS.config) | |
239 | cmd = SL.split(ENV['SSH_ORIGINAL_COMMAND']) | |
71d74dcf | 240 | if args: raise U.ExpectedError, (500, 'Unexpected arguments via SSH') |
a2916c06 MW |
241 | return cmd |
242 | ||
243 | if 'CHPWD_SSH_USER' in ENV: | |
244 | ## Setting `CHPWD_SSH_USER' to a user name is the administrator's way | |
245 | ## of telling us that this is a user request, so treat it like Userv. | |
246 | ||
247 | with cli_errors(): | |
248 | cmd = ssh_setup() | |
249 | CU.set_user(ENV['CHPWD_SSH_USER']) | |
a2916c06 MW |
250 | with OUT.redirect_to(O.FileOutput()): |
251 | OPTPARSE.dispatch('userv', cmd) | |
252 | ||
253 | elif 'CHPWD_SSH_MASTER' in ENV: | |
254 | ## Setting `CHPWD_SSH_MASTER' to anything tells us that the client is | |
255 | ## making a remote-service request. We must turn on the protocol | |
256 | ## decoration machinery, but don't need to -- mustn't, indeed -- set up | |
257 | ## a user. | |
258 | ||
259 | try: | |
260 | cmd = ssh_setup() | |
261 | with OUT.redirect_to(O.RemoteOutput()): | |
71d74dcf MW |
262 | OPTPARSE.dispatch('remote', map(CGI.urldecode, cmd)) |
263 | except U.ExpectedError, e: | |
a2916c06 MW |
264 | print 'ERR', e.code, e.msg |
265 | else: | |
266 | print 'OK' | |
267 | ||
268 | else: | |
269 | ## There's probably some strange botch in the `.ssh/authorized_keys' | |
270 | ## file, but we can't do much about it from here. | |
271 | ||
272 | with cli_errors(): | |
71d74dcf | 273 | raise U.ExpectedError, (400, "Unabled to determine SSH context") |
a2916c06 MW |
274 | |
275 | else: | |
276 | ## Plain old command line, apparently. We default to administration | |
277 | ## commands, but allow any kind, since this is useful for debugging, and | |
278 | ## this isn't a security problem since our caller is just as privileged | |
279 | ## as we are. | |
280 | ||
281 | with cli_errors(): | |
282 | OPTS, args = OPTPARSE.parse_args() | |
283 | CONF.loadconfig(OPTS.config) | |
bb623e8f | 284 | CGI.SSLP = OPTS.sslp |
a2916c06 MW |
285 | ctx = OPTS.context |
286 | if OPTS.user: | |
287 | CU.set_user(OPTS.user) | |
ea3f041b | 288 | CGI.STATE.kw['user'] = OPTS.user |
a2916c06 MW |
289 | if ctx is None: ctx = 'userv' |
290 | else: | |
291 | D.opendb() | |
292 | if ctx is None: ctx = 'admin' | |
293 | with OUT.redirect_to(O.FileOutput()): | |
294 | OPTPARSE.dispatch(ctx, args) | |
295 | ||
296 | ###----- That's all, folks -------------------------------------------------- |