Imported Upstream version 1.10.2
[platform/upstream/krb5.git] / doc / kadm5 / api-server-design.tex
1 \documentstyle[12pt,fullpage,rcsid]{article}
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 %% Make _ actually generate an _, and allow line-breaking after it.
5 \let\underscore=\_
6 \catcode`_=13
7 \def_{\underscore\penalty75\relax}
8 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
9
10 \rcs$Id$
11
12 \setlength{\parskip}{.7\baselineskip}
13 \setlength{\parindent}{0pt}
14
15 \def\v#1{\verb+#1+}
16 \def\k#1{K$_#1$}
17
18 \title{KADM5 Library and Server \\ Implementation Design\thanks{\rcsId}}
19 \author{Barry Jaspan}
20
21 \begin{document}
22
23 \sloppy
24 \maketitle
25
26 {\setlength{\parskip}{0pt}\tableofcontents}
27
28 \section{Overview}
29
30 The KADM5 administration system is designed around the KADM5 API.  The
31 ``server-side'' library libkadm5srv.a implements the KADM5 API by
32 operating directly on the underlying KDC and admin databases.  The
33 ``client-side'' library libkadm5clnt.a implements the KADM5 API via an
34 RPC mechanism.  The administration server kadmind accepts RPC requests
35 from the client-side library and translates them into calls to the
36 server-side library, performing authentication, authorization, and
37 logging along the way.
38
39 The two libraries, libkadm5clnt.a and libkadm5srv.a, export the
40 identical kadm5 interface; for example, both contain definitions for
41 kadm5_get_principal, and all other kadm5 functions.  In most cases,
42 the client library function just marshalls arguments and results into
43 and out of an RPC call, whereas the server library function performs
44 the actual operation on the database file.  kadm5_init_*, however, are
45 substantially different even though they export the same interface: on
46 the client, they establish the RPC connection and GSS-API context,
47 whereas on the server side the open the database files, read in the
48 password dictionary, and the like.  Also, the kadm5_free functions
49 operate on local process memory in both libraries.
50
51 The admin server is implemented as a nearly-stateless transaction
52 server, where each admin API function represents a single transaction.
53 No per-client or per-connection information is stored; only local
54 database handles are maintained between requests.  The RPC mechanism
55 provides access to remote callers' authentication credentials for
56 authorization purposes.
57
58 The admin API is exported via an RPC interface that hides all details
59 about network encoding, authentication, and encryption of data on the
60 wire.  The RPC mechanism does, however, allow the server to access the
61 underlying authentication credentials for authorization purposes.
62
63 The admin system maintains two databases:
64 %
65 \begin{itemize}
66 \item The master Kerberos (KDC) database is used to store all the
67 information that the Kerberos server understands, thus allowing the
68 greatest functionality with no modifications to a standard KDC.  
69
70 \item The KDC database also stores kadm5-specific per-principal
71 information in each principal's krb5_tl_data list.  In a prior
72 version, this data was stored in a separate admin principal database;
73 thus, when this document refers to ``the admin principal database,''
74 it now refers to the appropriate krb5_tl_data entries in the KDC
75 database.
76
77 \item The policy database stores kadm5 policy information.
78 \end{itemize}
79
80 The per-principal information stored in the admin principal database
81 consists of the principal's policy name and an array of the
82 principal's previous keys.  The old keys are stored encrypted in the
83 key of the special principal ``kadmin/history'' that is created by the
84 server library when it is first needed.  Since a change in
85 kadmin/history's key renders every principal's key history array
86 useless, it can only be changed using the ovsec_adm_edit utility; that
87 program will reencrypt every principal's key history in the new
88 key.\footnote{ovsec_adm_edit has not yet been implemented, and there
89 are currently no plans to implement it; thus, the history cannot
90 currently be changed.}  The server library refuses all requests to
91 change kadmin/history's key.
92
93 \section{API Handles}
94
95 Each call to kadm5_init_* on the client or server creates a new API
96 handle.  The handles encapsulate the API and structure versions
97 specified by kadm5_init_*'s caller and all other internal data needed
98 by the library.  A process can have multiple open API handles
99 simultaneously by calling kadm5_init_* multiple times, and call can
100 specify a different version, client or service principal, and so
101 forth.
102
103 Each kadm5 function verifies the handle it is given with the
104 CHECK_HANDLE or _KADM5_CHECK_HANDLE macros.  The CHECK_HANDLE macro
105 differs for the client and server library because the handle types
106 used by those libraries differ, so it is defined in both
107 $<$client_internal.h$>$ and $<$server_internal.h$>$ in the library
108 source directory.  In each header file, CHECK_HANDLE first calls
109 GENERIC_CHECK_HANDLE, defined in $<$admin_internal.h$>$, which
110 verifies the magic number, API version, and structure version that is
111 contained in both client and server handles.  CHECK_HANDLE then calls
112 either CLIENT_CHECK_HANDLE or SERVER_CHECK_HANDLE respectively to
113 verify the client- or server-library specific handle fields.
114
115 The CHECK_HANDLE macro is useful because it inlines the handle check
116 instead of requiring a separate function call.  However, using
117 CHECK_HANDLE means that a source file cannot be compiled once and
118 included into both the client and server library, because CHECK_HANDLE
119 is always either specific to either the client or server library, not
120 both.  There are a number of functions that can be implemented with
121 the same code in both the client and server libraries, however,
122 including all of the kadm5_free functions and
123 kadm5_chpass_principal_util.  The _KADM5_CHECK_HANDLE macro solves
124 this problem; instead of inlining the handle check, it calls the
125 function _kadm5_check_handle which is defined separately in both the
126 client and server library, in client_init.c and server_init.c.
127 Since these two files are only compiled once and put in a single
128 library, they simply verify the handle they are passed with
129 CHECK_HANDLE and return the result.
130
131 \section{API Versioning}
132
133 The KADM5 system was designed by OpenVision to support multiple
134 versions of the KADM5 API.  MIT has not adopted this level of support,
135 and considers the KADM5 C API to be unstable from release to release.
136 This section describes the original design intent; bear in mind that
137 only the most recent API is supported by current MIT krb5 releases,
138 and that the API version does not necessarily change with API changes
139 unless there is a need to do so for wire compatibility.
140
141 Historically, three versions of the KADM5 API have existed:
142 KADM5_API_VERSION_1 through KADM5_API_VERSION_3.  The first version
143 was equivalent to the initial OpenVision API,
144 OVSEC_KADM_API_VERSION_1; the second was created during the initial
145 integration of the OpenVision system into the MIT release; and the
146 third was created for MIT krb5 1.8 to add lockout fields to policy
147 entries.  MIT dropped wire compatibility support for version 1 in MIT
148 krb5 1.8 (as version 1 was never used in shipped MIT code), but
149 retains wire compatibility support for version 2.
150
151 Implementing a versioned API in C via with both local and RPC access
152 presents a number of design issues, some of them quite subtle.  The
153 contexts in which versioning considerations must be made include:
154
155 \begin{enumerate}
156 \item Typedefs, function declarations, and defined constants depend on
157 the API version a client is written to and must be correct at compile
158 time.
159
160 \item Each function in the server library must behave according to the
161 API version specified by the caller at runtime to kadm5_init_*.
162
163 \item The XDR functions used by the RPC layer to transmit function
164 arguments and results must encode data structures correctly depending
165 on the API version specified by the client at runtime.
166
167 \item Each function in the client library must behave according to the
168 API version specified by the caller at runtime to kadm5_init_*.
169
170 \item The RPC server (kadmind) must accept calls from a client using
171 any supported API version, and must then invoke the function in the
172 server library corresponding to the RPC with the API version indicated
173 by the client caller.
174
175 \item When a first API function is invoked that needs to call a second
176 function in the API on its own behalf, and that second API function's
177 behavior depends on the API version specified, the first API function
178 must either be prepared to call the second API function at whatever
179 version its caller specifies or have a means of always calling the
180 second API function at a pre-determined version.
181 \end{enumerate}
182
183 The following functions describe how each context is handled.
184
185 \subsection{Designing for future compatibility}
186
187 Any code whose behavior depends on the API version should be written
188 so as to be compatible with future, currently unknown API versions on
189 the grounds that any particuarly piece of API behavior will most
190 likely not change between versions.  For example, in the current
191 system, the code is not written as ``if this is VERSION_1, do X, else
192 if this is VERSION_2, do Y''; instead, it is written as ``if this is
193 VERSION_1, do X; else, do Y.''  The former will require additional
194 work when VERSION_3 is defined, even if ``do Y'' is still the correct
195 action, whereas the latter will work without modification in that
196 case.
197
198 \subsection{Header file declarations}
199
200 Typedefs, defined constants and macros, and function declarations may
201 change between versions.  A client is always written to a single,
202 specific API version, and thus expects the header files to define
203 everything according to that API.  Failure of a header file to define
204 values correctly will result in either compiler warnings (e.g. if the
205 pointer type of a function argument changes) or fatal errors (e.g. if
206 the number of arguments to a function changes, or the fields of a
207 structure change).  For example, in VERSION_1, kadm5_get_policy took a
208 pointer to a pointer to a structure, and in VERSION_2 it takes a
209 pointer to a structure; that would generate a warning if not correct.
210 In VERSION_1, kadm5_randkey_principal accepted three arguments but in
211 VERSION_2 accepts four; that would generate a fatal error.
212
213 The header file defines everything correctly based on the value of the
214 USE_KADM5_API_VERSION constant.  The constant can be assigned to an
215 integer corresponding to any supported API version, and defaults to
216 the newest version.  The header files then simply use an \#ifdef to
217 include the right definitions:
218 %
219 \begin{verbatim}
220 #if USE_KADM5_API_VERSION == 1
221 kadm5_ret_t    kadm5_get_principal(void *server_handle,
222                                    krb5_principal principal,
223                                    kadm5_principal_ent_t *ent);
224 #else
225 kadm5_ret_t    kadm5_get_principal(void *server_handle,
226                                    krb5_principal principal,
227                                    kadm5_principal_ent_t ent,
228                                    long mask);
229 #endif
230 \end{verbatim}
231
232 \subsection{Server library functions}
233
234 Server library functions must know how many and what type of arguments
235 to expect, and must operate on those arguments correctly, based on the
236 API version with which they are invoked.  The API version is contained
237 in the handle that is alwasy passed as their first argument, generated
238 by kadm5_init_* (to which the client specified the API version to use
239 at run-time).
240
241 In general, it is probably unsafe for a compiled function in a library
242 to re-interpret the number and type of defined arguments at run-time
243 since the calling conventions may not allow it; for example, a
244 function whose first argument was a short in one version and a pointer
245 in the next might fail if it simply typed-casted the argument.  In
246 that case, the function would have to written to take variable
247 arguments (i.e. use $<$stdarg.h$>$) and extract them from the stack
248 based on the API version.  Alternatively, a separate function for each
249 API version could be defined, and $<$kadm5/admin.h$>$ could be written
250 to \v{\#define} the exported function name based on the value of
251 USE_KADM5_API_VERSION.
252
253 In the current system, it turns out, that isn't necessary, and future
254 implementors should take try to ensure that no version has semantics
255 that will cause such problems in the future.  All the functions in
256 KADM5 that have different arguments or results between VERSION_1 and
257 VERSION_2 do so simply by type-casting their arguments to the
258 appropriate version and then have separate code paths to handle each
259 one correctly.  kadm5_get_principal, in svr_principal.c, is a good
260 example.  In VERSION_1, it took the address of a pointer to a
261 kadm5_principal_ent_t to fill in with a pointer to allocated memory;
262 in VERSION_2, it takes a pointer to a structure to fill in, and a mask
263 of which fields in that structure should be filled in.  Also, the
264 contents of the kadm5_principal_ent_t changed slightly between the two
265 versions.  kadm5_get_principal handles versioning as follows
266 (following along in the source code will be helpful):
267
268 \begin{enumerate}
269 \item If VERSION_1, it saves away its entry argument (address of a
270 pointer to a structure) and resets its value to contain the address of
271 a locally stack-allocated entry structure; this allows most of the
272 function to written once, in terms of VERSION_2 semantics.  If
273 VERSION_1, it also resets its mask argument to be
274 KADM5_PRINCIPAL_NORMAL_MASK, because that is the equivalent to
275 VERSION_1 behavior, which was to return all the fields of the
276 structure.
277
278 \item The bulk of the function is implemented as expected for
279 VERSION_2.
280
281 \item The new fields in the VERSION_2 entry structure are assigned
282 inside a block that is only execute if the caller specified
283 VERSION_2.  This saves a little time for a VERSION_1 caller.
284
285 \item After the entry structure is filled, the function checks again
286 if it was called as VERSION_1.  If so, it allocates a new
287 kadm5_principal_ent_t_v1 structure (which is conveniently defined in
288 the header file) with malloc, copies the appropriate values from the
289 entry structure into the VERSION_1 entry structure, and then writes
290 the address of the newly allocated memory into address specified by
291 the original entry argument which it had previously saved away.
292 \end{enumerate}
293
294 There is another complication involved in a function re-interpreting
295 the number of arguments it receives at compile time---it cannot assign
296 any value to an argument for which the client did not pass a value.
297 For example, a VERSION_1 client only passes three arguments to
298 kadm5_get_principal.  If the implementation of kadm5_get_principal
299 notices that the caller is VERSION_1 and therefore assigns its fourth
300 argument, mask, to a value that mimics the VERSION_1 behavior, it may
301 inadvertently overwrite data on its caller's stack.  This problem can
302 be avoided simply by using a true local variable in such cases,
303 instead of treating an unpassed argument as a local variable.
304
305 \subsection{XDR functions}
306
307 The XDR functions used to encode function arguments and results must
308 know how to encode the data for any API version.  This is important
309 both so that all the data gets correctly transmitted and so that
310 protocol compatibility between clients or servers using the new
311 library but an old API version is maintained; specific, new kadmind
312 servers should support old kadm5 clients.
313
314 The signature of all XDR functions is strictly defined: they take the
315 address of an XDR function and the address of the data object to be
316 encoded or decoded.  It is thus impossible to provide the API version
317 of the data object as an additional argument to an XDR function.
318 There are two other means to convey the information, storing the API
319 version to use as a field in the data object itself and creating
320 separate XDR functions to handle each different version of the data
321 object, and both of them are used in KADM5.
322
323 In the client library, each kadm5 function collects its arguments into
324 a single structure to be passed by the RPC; similarly, it expects all
325 of the results to come back as a single structure from the RPC that it
326 will then decode back into its constituent pieces (these are the
327 standard ONC RPC semantics).  In order to pass versioning information
328 to the XDR functions, each function argument and result datatype has a
329 filed to store the API version.  For example, consider
330 kadm5_get_principal's structures:
331 %
332 \begin{verbatim}
333 struct gprinc_arg {
334         krb5_ui_4 api_version;
335         krb5_principal princ;
336         long mask;
337 };
338 typedef struct gprinc_arg gprinc_arg;
339 bool_t xdr_gprinc_arg();
340
341 struct gprinc_ret {
342         krb5_ui_4 api_version;
343         kadm5_ret_t code;
344         kadm5_principal_ent_rec rec;
345 };
346 typedef struct gprinc_ret gprinc_ret;
347 bool_t xdr_gprinc_ret();
348 \end{verbatim}
349 %
350 kadm5_get_principal (in client_principal.c) assigns the api_version
351 field of the gprinc_arg to the version specified by its caller,
352 assigns the princ field based on its arguments, and assigns the mask
353 field from its argument if the caller specified VERSION_2.  It then
354 calls the RPC function clnt_call, specifying the XDR functions
355 xdr_gprinc_arg and xdr_gprinc_ret to handle the arguments and results.
356
357 xdr_gprinc_arg is invoked with a pointer to the gprinc_arg structure
358 just described.  It first encodes the api_version field; this allows
359 the server to know what to expect.  It then encodes the krb5_principal
360 structure and, if api_version is VERSION_2, the mask.  If api_version
361 is not VERSION_2, it does not encode {\it anything} in place of the
362 mask, because an old VERSION_1 server will not expect any other data
363 to arrive on the wire there.
364
365 The server performs the kadm5_get_principal call and returns its
366 results in an XDR encoded gprinc_ret structure.  clnt_call, which has
367 been blocking until the results arrived, invokes xdr_gprinc_ret with a
368 pointer to the encoded data for it to decode.  xdr_gprinc_ret first
369 decodes the api_version field, and then the code field since that is
370 present in all versions to date.  The kadm5_principal_ent_rec presents
371 a problem, however.  The structure does not itself contain an
372 api_version field, but the structure is different between the two
373 versions.  Thus, a single XDR function cannot decode both versions of
374 the structure because it will have no way to decide which version to
375 expect.  The solution is to have two functions,
376 kadm5_principal_ent_rec_v1 and kadm5_principal_ent_rec, which always
377 decode according to VERSION_1 or VERSION_2, respectively.  gprinc_ret
378 knows which one to invoke because it has the api_version field
379 returned by the server (which is always the same as that specified by
380 the client in the gpring_arg).
381
382 In hindsight, it probably would have been better to encode the API
383 version of all structures directly in a version field in the structure
384 itself; then multiple XDR functions for a single data type wouldn't be
385 necessary, and the data objects would stand complete on their own.
386 This can be added in a future API version if desired.
387
388 \subsection{Client library functions}
389
390 Just as with server library functions, client library functions must
391 be able to interpret their arguments and provide result according to
392 the API version specified by the caller.  Again, kadm5_get_principal
393 (in client_principal.c) is a good example.  The gprinc_ret structure
394 that it gets back from clnt_call contains a kadm5_principal_ent_rec or
395 a kadm5_principal_ent_rec_v1 (the logic is simplified somewhat because
396 the VERSION_2 structure only has new fields added on the end).  If
397 kadm5_get_principal was invoked with VERSION_2, that structure should
398 be copied into the pointer provided as the entry argument; if it was
399 invoked with VERSION_1, however, the structure should be copied into
400 allocated memory whose address is then written into the pointer
401 provided by the entry argument.  Client library functions make this
402 determination based on the API version specified in the provided
403 handle, just like server library functions do.
404
405 \subsection{Admin server stubs}
406
407 When an RPC call arrives at the server, the RPC layer authenticates
408 the call using the GSS-API, decodes the arguments into their
409 single-structure form (ie: a gprinc_arg) and dispatches the call to a
410 stub function in the server (in server_stubs.c).  The stub function
411 first checks the caller's authorization to invoke the function and, if
412 authorized, calls the kadm5 function corresponding to the RPC function
413 with the arguments specified in the single-structure argument.
414
415 Once again, kadm5_get_principal is a good example for the issues
416 involved.  The contents of the gprinc_arg given to the stub
417 (get_principal_1) depends on the API version the caller on the client
418 side specified; that version is available to the server in the
419 api_version field of the gprinc_arg.  When the server calls
420 kadm5_get_principal in the server library, it must give that function
421 an API handle that contains the API version requested by the client;
422 otherwise the function semantics might not be correct.  One
423 possibility would be for the server to call kadm5_init for each client
424 request, specifing the client's API version number and thus generating
425 an API handle with the correct version, but that would be
426 prohibitively inefficient.  Instead, the server dips down in the
427 server library's internal abstraction barrier, using the function
428 new_server_handle to cons up a server handle based on the server's own
429 global_server_handle but using the API version specified by the
430 client.  The server then passes the newly generated handle to
431 kadm5_get_principal, ensuring the right behavior, and creates the
432 gprinc_ret structure in a manner similar to that described above.
433
434 Although new_server_handle solves the problem of providing the server
435 with an API handle containing the right API version number, it does
436 not solve another problem: that a single source file, server_stubs.c,
437 needs to be able to invoke functions with arguments appropriate for
438 multiple API versions.  If the client specifies VERSION_1, for
439 example, the server must invoke kadm5_get_principal with three
440 arguments, but if the client specifies VERSION_2 the server must
441 invoke kadm5_get_principal with four arguments.  The compiler will not
442 allow this inconsistency.  The server defines wrapper functions in a
443 separate source file that match the old version, and the separate
444 source file is compiled with USE_KADM5_API_VERSION set to the old
445 version; see kadm5_get_principal_v1 in server_glue_v1.c.  The server
446 then calls the correct variant of kadm5_get_principal_* based on the
447 API version and puts the return values into the gprinc_ret in a manner
448 similar to that described above.
449
450 Neither of these solutions are necessarily correct.  new_server_handle
451 violates the server library's abstraction barrier and is at best a
452 kludge; the server library should probably export a function to
453 provide this behavior without violating the abstraction;
454 alternatively, the librar should be modified so that having the server
455 call kadm5_init for each client RPC request would not be too
456 inefficient.  The glue functions in server_glue_v1.c really are not
457 necessary, because the server stubs could always just pass dummy
458 arguments for the extra arguments; after all, the glue functions pass
459 {\it nothing} for the extra arguments, so they just end up as stack
460 garbage anyway.
461
462 Another alternative to the new_server_handle problem is to have the
463 server always invoke server library functions at a single API version,
464 and then have the stubs take care of converting the function arguments
465 and results back into the form expected by the caller.  In general,
466 however, this might require the stubs to duplicate substantial logic
467 already present in the server library and further violate the server
468 library's abstraction barrier.
469
470 \subsection{KADM5 self-reference}
471
472 Some kadm5 functions call other kadm5 functions ``on their own
473 behalf'' to perform functionality that is necessary but that does not
474 directly affect what the client sees.  For example,
475 kadm5_chpass_principal has to enforce password policies; thus, it
476 needs to call kadm5_get_principal and, if the principal has a policy,
477 kadm5_get_policy and kadm5_modify_principal in the process of changing
478 a principal's password.  This leads to a complication: what API handle
479 should kadm5_chpass_principal pass to the other kadm5 functions it
480 calls?
481
482 The ``obvious,'' but wrong, answer is that it should pass the handle
483 it was given by its caller.  The caller may provide an API handle
484 specifying any valid API version.  Although the semantics of
485 kadm5_chpass_principal did not change between VERSION_1 and VERSION_2,
486 the declarations of both kadm5_get_principal and kadm5_get_policy
487 did.  Thus, to use the caller's API handle, kadm5_chpass_principal
488 will have to have a separate code path for each API version, even
489 though it itself did not change bewteen versions, and duplicate a lot
490 of logic found elsewhere in the library.
491
492 Instead, each API handle contains a ``local-use handle,'' or lhandle,
493 that kadm5 functions should use to call other kadm5 functions.  For
494 example, the client-side library's handle structure is:
495 %
496 \begin{verbatim}
497 typedef struct _kadm5_server_handle_t {
498         krb5_ui_4       magic_number;
499         krb5_ui_4       struct_version;
500         krb5_ui_4       api_version;
501         char *          cache_name;
502         int             destroy_cache;
503         CLIENT *        clnt;
504         krb5_context    context;
505         kadm5_config_params params;
506         struct _kadm5_server_handle_t *lhandle;
507 } kadm5_server_handle_rec, *kadm5_server_handle_t;
508 \end{verbatim}
509 %
510 The lhandle field is allocated automatically when the handle is
511 created.  All of the fields of the API handle that are accessed
512 outside kadm5_init are also duplicated in the lhandle; however, the
513 api_version field of the lhandle is always set to a {\it constant}
514 value, regardless of the API version specified by the caller to
515 kadm5_init.  In the current implementation, the lhandle's api_version
516 is always VERSION_2.
517
518 By passing the caller's handle's lhandle to recursively called kadm5
519 functions, a kadm5 function is assured of invoking the second kadm5
520 function with a known API version.  Additionally, the lhandle's
521 lhandle field points back to the lhandle, in case kadm5 functions call
522 themselves more than one level deep; handle$->$lhandle always points
523 to the same lhandle, no matter how many times the indirection is
524 performed.
525
526 This scheme might break down if a kadm5 function has to call another
527 kadm5 function to perform operations that they client will see and for
528 its own benefit, since the semantics of the recursively-called kadm5
529 function may depend on the API version specified and the client may be
530 depending on a particular version's behavior.  Future implementators
531 should avoid creating a situation in which this is possible.
532
533 \section{Server Main}
534
535 The admin server starts by trapping all fatal signals and directing
536 them to a cleanup-and-exit function.  It then creates and exports the
537 RPC interface and enters its main loop.
538
539 The main loop dispatches all incoming requests to the RPC mechanism.
540 In a previous version, after 15 seconds of inactivity, the server
541 closed all open databases; each database was be automatically reopened
542 by the API function implementations as necessary.  That behavior
543 existed to protect against loss of written data before the process
544 exited.  The current database libraries write all changes out to disk
545 immediately, however, so this behavior is no longer required or
546 performed.
547
548 \section{Remote Procedure Calls}
549
550 The RPC for the Admin system will be based on ONC RPC.  ONC RPC is
551 used because it is a well-known, portable RPC mechanism.  The
552 underlying external data representation (xdr) mechanisms for wire
553 encapsulation are well-known and extensible.  Authentication to the
554 admin server and encryption of all RPC functional arguments and
555 results are be handled via the AUTH_GSSAPI authentication flavor of
556 ONC RPC.
557
558 \section{Database Record Types}
559 \label{sec:db-types}
560
561 \subsection{Admin Principal, osa_princ_ent_t}
562
563 The admin principal database stores records of the type
564 osa_princ_ent_t (declared in $<$kadm5/adb.h$>$), which is the
565 subset of the kadm5_principal_ent_t structure that is not stored
566 in the Kerberos database plus the necessary bookkeeping information.
567 The records are keyed by the ASCII representation of the principal's
568 name, including the trailing NULL.
569
570 \begin{verbatim}
571 typedef struct _osa_pw_hist_t {
572      int n_key_data;
573      krb5_key_data *key_data;
574 } osa_pw_hist_ent, *osa_pw_hist_t;
575
576 typedef struct _osa_princ_ent_t {
577         char * policy;
578         u_int32 aux_attributes;
579
580         unsigned int old_key_len;
581         unsigned int old_key_next;
582         krb5_kvno admin_history_kvno;
583         osa_pw_hist_ent *old_keys;
584
585
586         u_int32 num_old_keys;
587         u_int32 next_old_key;
588         krb5_kvno admin_history_kvno;
589         osa_pw_hist_ent *old_keys;
590 } osa_princ_ent_rec, *osa_princ_ent_t;
591 \end{verbatim}
592
593 The fields that are different from kadm5_principal_ent_t are:
594
595 \begin{description}
596 \item[num_old_keys] The number of previous keys in the old_keys array.
597 This value must be 0 $\le$ num_old_keys $<$ pw_history_num.
598
599 \item[old_key_next] The index into old_keys where the next key should
600 be inserted.  This value must be 0 $\le$ old_key_next $\le$
601 num_old_keys.
602
603 \item[admin_history_kvno] The key version number of the kadmin/history
604 principal's key used to encrypt the values in old_keys.  If the server
605 library finds that kadmin/history's kvno is different from the value
606 in this field, it returns KADM5_BAD_HIST_KEY.
607
608 \item[old_keys] The array of the principal's previous passwords, each
609 encrypted in the kadmin/history key.  There are num_old_keys
610 elements.  Each ``password'' in the array is itself an array of
611 n_key_data krb5_key_data structures, one for each keysalt type the
612 password was encoded in.
613 \end{description}
614
615 \subsection{Policy, osa_policy_ent_t}
616
617 The policy database stores records of the type osa_policy_ent_t
618 (declared in $<$kadm5/adb.h$>$) , which is all of
619 kadm5_policy_ent_t plus necessary bookkeeping information.  The
620 records are keyed by the policy name.
621
622 \begin{verbatim}
623 typedef struct _osa_policy_ent_t {
624         char *policy;
625
626         u_int32 pw_min_life;
627         u_int32 pw_max_life;
628         u_int32 pw_min_length;
629         u_int32 pw_min_classes;
630         u_int32 pw_history_num;
631
632         u_int32 refcnt;
633 } osa_policy_ent_rec, *osa_policy_ent_t;
634 \end{verbatim}
635
636 \subsection{Kerberos, krb5_db_entry}
637
638 The Kerberos database stores records of type krb5_db_entry, which is
639 defined in the $<$k5-int.h$>$ header file.  The semantics of each
640 field are defined in the libkdb functional specification.
641
642 \section{Database Access Methods}
643
644 \subsection{Principal and Policy Databases}
645
646 This section describes the database abstraction used for the admin
647 policy database; the admin principal database used to be treated in
648 the same manner but is now handled more directly as krb5_tl_data;
649 thus, nothing in this section applies to it any more.  Since both
650 databases export equivalent functionality, the API is only described
651 once.  The character T is used to represent both ``princ'' and
652 ``policy''. The location of the principal database is defined by the
653 configuration parameters given to any of the kadm5_init functions in
654 the server library.
655
656 Note that this is {\it only} a database abstraction.  All functional
657 intelligence, such as maintaining policy reference counts or sanity
658 checking, must be implemented above this layer.
659
660 Prototypes for the osa functions are supplied in
661 $<$kadm5/adb.h$>$. The routines are defined in libkadm5srv.a. They
662 require linking with the Berkely DB library.
663
664 \subsubsection{Error codes}
665
666 The database routines use com_err for error codes.  The error code
667 table name is ``adb'' and the offsets are the same as the order
668 presented here. The error table header file is
669 $<$kadm5/adb_err.h$>$. Callers of the OSA routines should first call
670 init_adb_err_tbl() to initialize the database table.
671
672 \begin{description}
673 \item[OSA_ADB_OK] Operation successful.
674 \item[OSA_ADB_FAILURE] General failure.
675 \item[OSA_ADB_DUP] Operation would create a duplicate database entry.
676 \item[OSA_ADB_NOENT] Named entry not in database.
677 \item[OSA_ADB_BAD_PRINC] The krb5_principal structure is invalid.
678 \item[OSA_ADB_BAD_POLICY] The specified policy name is invalid.
679 \item[OSA_ADB_XDR_FAILURE] The principal or policy structure cannot be
680 encoded for storage.
681 \item[OSA_ADB_BADLOCKMODE] Bad lock mode specified.
682 \item[OSA_ADB_CANTLOCK_DB] Cannot lock database, presumably because it
683 is already locked.
684 \item[OSA_ADB_NOTLOCKED] Internal error, database not locked when
685 unlock is called.
686 \item[OSA_ADB_NOLOCKFILE] KADM5 administration database lock file missing.
687 \end{description}
688
689 Database functions can also return system errors.  Unless otherwise
690 specified, database functions return OSA_ADB_OK.
691
692 \subsubsection{Locking}
693
694 All of the osa_adb functions except open and close lock and unlock the
695 database to prevent concurrency collisions.  The overall locking
696 algorithm is as follows:
697
698 \begin{enumerate}
699 \item osa_adb_open_T calls osa_adb_init_db to allocate the osa_adb_T_t
700 structure and open the locking file for further use.
701
702 \item Each osa_adb functions locks the locking file and opens the
703 appropriate database with osa_adb_open_and_lock, performs its action,
704 and then closes the database and unlocks the locking file with
705 osa_adb_close_and_unlock.
706
707 \item osa_adb_close_T calls osa_adb_fini_db to close the locking file
708 and deallocate the db structure.
709 \end{enumerate}
710
711 Functions which modify the database acquire an exclusive lock, others
712 acqure a shared lock.  osa_adb_iter_T acquires an exclusive lock for
713 safety but as stated below consequences of modifying the database in
714 the iteration function are undefined.
715
716 \subsubsection{Function descriptions}
717
718 \begin{verbatim}
719 osa_adb_ret_t osa_adb_create_T_db(kadm5_config_params *params)
720 \end{verbatim}
721 %
722 Create the database and lockfile specified in params.  The database
723 must not already exist, or EEXIST is returned.  The lock file is only
724 created after the database file has been created successfully.
725
726 \begin{verbatim}
727 osa_adb_ret_t osa_adb_rename_T_db(kadm5_config_params *fromparams,
728                                   kadm5_config_params *toparams)
729 \end{verbatim}
730 %
731 Rename the database named by fromparams to that named by toparams.
732 The fromparams database must already exist; the toparams database may
733 exist or not.  When the function returns, the database named by
734 fromparams no longer exists, and toparams has been overwritten with
735 fromparams.  This function acquires a permanent lock on both databases
736 for the duration of its operation, so a failure is likely to leave the
737 databases unusable.
738
739 \begin{verbatim}
740 osa_adb_ret_t osa_adb_destroy_policy_db(kadm5_config_params *params)
741 \end{verbatim}
742 %
743 Destroy the database named by params.  The database file and lock file
744 are deleted.
745
746 \begin{verbatim}
747 osa_adb_ret_t
748 osa_adb_open_T(osa_adb_T_t *db, char *filename);
749 \end{verbatim}
750 %
751 Open the database named filename.  Returns OSA_ADB_NOLOCKFILE if the
752 database does not exist or if the lock file is missing.  The database
753 is not actually opened in the operating-system file sense until a lock
754 is acquire.
755
756 \begin{verbatim}
757 osa_adb_ret_t
758 osa_adb_close_T(osa_adb_T_t db);
759 \end{verbatim}
760 %
761 Release all shared or exclusive locks (on BOTH databases, since they
762 use the same lock file) and close the database.
763
764 It is an error to exit while a permanent lock is held;
765 OSA_ADB_NOLOCKFILE is returned in this case.
766
767 \begin{verbatim}
768 osa_adb_ret_t osa_adb_get_lock(osa_adb_T_t db, int mode)
769 \end{verbatim}
770
771 Acquire a lock on the administration databases; note that both
772 databases are locked simultaneously by a single call.  The mode
773 argument can be OSA_ADB_SHARED, OSA_ADB_EXCLUSIVE, or
774 OSA_ADB_PERMANENT.  The first two and the third are really disjoint
775 locking semantics and should not be interleaved.
776
777 Shared and exclusive locks have the usual semantics, and a program can
778 upgrade a shared lock to an exclusive lock by calling the function
779 again.  A reference count of open locks is maintained by this function
780 and osa_adb_release_lock so the functions can be called multiple
781 times; the actual lock is not released until the final
782 osa_adb_release_lock.  Note, however, that once a lock is upgraded
783 from shared to exclusive, or from exclusive to permanent, it is not
784 downgraded again until released completely.  In other words,
785 get_lock(SHARED), get_lock(EXCLUSIVE), release_lock() leaves the
786 process with an exclusive lock with a reference count of one.  An
787 attempt to get a shared or exclusive lock that conflicts with another
788 process results in the OSA_ADB_CANLOCK_DB error code.
789
790 This function and osa_adb_release_lock are called automatically as
791 needed by all other osa_adb functions to acquire shared and exclusive
792 locks and so are not normally needed.  They can be used explicitly by
793 a program that wants to perform multiple osa_adb functions within the
794 context of a single lock.
795
796 Acquiring an OSA_ADB_PERMANENT lock is different.  A permanent lock
797 consists of first acquiring an exclusive lock and then {\it deleting
798 the lock file}.  Any subsequent attempt to acquire a lock by a
799 different process will fail with OSA_ADB_NOLOCKFILE instead of
800 OSA_ADB_CANTLOCK_DB (attempts in the same process will ``succeed''
801 because only the reference count gets incremented).  The lock file is
802 recreated by osa_adb_release_lock when the last pending lock is released.
803
804 The purpose of a permanent lock is to absolutely ensure that the
805 database remain locked during non-atomic operations.  If the locking
806 process dies while holding a permanent lock, all subsequent osa_adb
807 operations will fail, even through a system reboot.  This is useful,
808 for example, for ovsec_adm_import which creates both new database
809 files in a temporary location and renames them into place.  If both
810 renames do not fully complete the database will probably be
811 inconsistent and everything should stop working until an administrator
812 can clean it up.
813
814 \begin{verbatim}
815 osa_adb_ret_t osa_adb_release_lock(osa_adb_T_t db)
816 \end{verbatim}
817
818 Releases a shared, exclusive, or permanent lock acquired with
819 osa_adb_get_lock, or just decrements the reference count if multiple
820 locks are held.  When a permanent lock is released, the lock file is
821 re-created.
822
823 All of a process' shared or exclusive database locks are released when
824 the process terminates.  A permanent lock is {\it not} released when
825 the process exits (although the exclusive lock it begins with
826 obviously is).
827
828 \begin{verbatim}
829 osa_adb_ret_t
830 osa_adb_create_T(osa_adb_T_t db, osa_T_ent_t entry);
831 \end{verbatim}
832 %
833 Adds the entry to the database.  All fields are defined.  Returns
834 OSA_ADB_DUP if it already exists.
835
836 \begin{verbatim}
837 osa_adb_ret_t
838 osa_adb_destroy_T(osa_adb_T_t db, osa_T_t name);
839 \end{verbatim}
840
841 Removes the named entry from the database.  Returns OSA_ADB_NOENT if
842 it does not exist.
843
844 \begin{verbatim}
845 osa_adb_ret_t
846 osa_adb_get_T(osa_adb_T_t db, osa_T_t name,
847         osa_princ_ent_t *entry); 
848 \end{verbatim}
849
850 Looks up the named entry in the db, and returns it in *entry in
851 allocated storage that must be freed with osa_adb_free_T.  Returns
852 OSA_ADB_NOENT if name does not exist, OSA_ADB_MEM if memory cannot be
853 allocated.
854
855 \begin{verbatim}
856 osa_adb_ret_t
857 osadb_adb_put_T(osa_adb_T_t db, osa_T_ent_t entry);
858 \end{verbatim}
859
860 Modifies the existing entry named in entry.  All fields must be filled
861 in.  Returns OSA_DB_NOENT if the named entry does not exist.  Note
862 that this cannot be used to rename an entry; rename is implemented by
863 deleting the old name and creating the new one (NOT ATOMIC!).
864
865 \begin{verbatim}
866 void osa_adb_free_T(osa_T_ent_t);
867 \end{verbatim}
868
869 Frees the memory associated with an osa_T_ent_t allocated by
870 osa_adb_get_T.
871
872 \begin{verbatim}
873 typedef osa_adb_ret_t (*osa_adb_iter_T_func)(void *data,
874                                     osa_T_ent_t entry);
875
876 osa_adb_ret_t osa_adb_iter_T(osa_adb_T_t db, osa_adb_iter_T_func func, 
877                     void *data);
878 \end{verbatim}
879
880 Iterates over every entry in the database.  For each entry ent in the
881 database db, the function (*func)(data, ent) is called.  If func
882 returns an error code, osa_adb_iter_T returns an error code.  If all
883 invokations of func return OSA_ADB_OK, osa_adb_iter_T returns
884 OSA_ADB_OK.  The function func is permitted to access the database,
885 but the consequences of modifying the database during the iteration
886 are undefined.
887
888 \subsection{Kerberos Database}
889
890 Kerberos uses the libkdb interface to store krb5_db_entry records.  It
891 can be accessed and modified in parallel with the Kerberos server,
892 using functions that are defined inside the KDC and the libkdb.a.  The
893 libkdb interface is defined in the libkdb functional specifications.
894
895 \subsubsection{Initialization and Key Access}
896
897 Keys stored in the Kerberos database are encrypted in the Kerberos
898 master key.  The admin server will therefore have to acquire the key
899 before it can perform any key-changing operations, and will have to
900 decrypt and encrypt the keys retrieved from and placed into the
901 database via krb5_db_get_principal and _put_principal.  This section
902 describes the internal admin server API that will be used to perform
903 these functions.
904
905 \begin{verbatim}
906 krb5_principal master_princ;
907 krb5_encrypt_block master_encblock;
908 krb5_keyblock master_keyblock;
909
910 void kdc_init_master()
911 \end{verbatim}
912
913 kdc_init_master opens the database and acquires the master key.  It
914 also sets the global variables master_princ, master_encblock, and
915 master_keyblock:
916
917 \begin{itemize}
918 \item master_princ is set to the name of the Kerberos master principal
919 (\v{K/M@REALM}).
920
921 \item master_encblock is something I have no idea about.
922
923 \item master_keyblock is the Kerberos master key
924 \end{itemize}
925
926 \begin{verbatim}
927 krb5_error_code kdb_get_entry_and_key(krb5_principal principal,
928                                       krb5_db_entry *entry,
929                                       krb5_keyblock *key)
930 \end{verbatim}
931
932 kdb_get_entry_and_key retrieves the named principal's entry from the
933 database in entry, and decrypts its key into key.  The caller must
934 free entry with krb5_dbm_db_free_principal and free key-$>$contents with
935 free.\footnote{The caller should also \v{memset(key-$>$contents, 0,
936 key-$>$length)}.  There should be a function krb5_free_keyblock_contents
937 for this, but there is not.}
938
939 \begin{verbatim}
940 krb5_error_code kdb_put_entry_pw(krb5_db_entry *entry, char *pw)
941 \end{verbatim}
942
943 kdb_put_entry_pw stores entry in the database.  All the entry values
944 must already be set; this function does not change any of them except
945 the key.  pw, the NULL-terminated password string, is converted to a
946 key using string-to-key with the salt type specified in
947 entry-$>$salt_type.\footnote{The salt_type should be set based on the
948 command line arguments to the kadmin server (see the ``Command Line''
949 section of the functional specification).}
950
951 \section{Admin Principal and Policy Database Implementation}
952
953 The admin principal and policy databases will each be stored in a
954 single hash table, implemented by the Berkeley 4.4BSD db library.
955 Each record will consist of an entire osa_T_ent_t.  The key into the
956 hash table is the entry name (for principals, the ASCII representation
957 of the name).  The value is the T entry structure.  Since the key and
958 data must be self-contained, with no pointers, the Sun xdr mechanisms
959 will be used to marshal and unmarshal data in the database.
960
961 The server in the first release will be single-threaded in that a
962 request will run to completion (or error) before the next will run,
963 but multiple connections will be allowed simultaneously.
964
965 \section{ACLs, acl_check}
966
967 The ACL mechanism described in the ``Authorization ACLs'' section of
968 the functional specifications will be implemented by the acl_check
969 function.
970
971 \begin{verbatim}
972 enum access_t {
973         ACCESS_DENIED = 0,
974         ACCESS_OK = 1,
975 };
976
977 enum access_t acl_check(krb5_principal princ, char *priv);
978 \end{verbatim}
979
980 The priv argument must be one of ``get'', ``add'', ``delete'', or
981 ``modify''.  acl_check returns 1 if the principal princ has the named
982 privilege, 0 if it does not.
983
984 \section{Function Details}
985
986 This section discusses specific design issues for Admin API functions
987 that are not addresed by the functional specifications.
988
989 \subsection{kadm5_create_principal}
990
991 If the named principal exists in either the Kerberos or admin
992 principal database, but not both, return KADM5_BAD_DB.
993
994 The principal's initial key is not stored in the key history array at
995 creation time.
996
997 \subsection{kadm5_delete_principal}
998
999 If the named principal exists in either the Kerberos or admin
1000 principal database, but not both, return KADM5_BAD_DB.
1001
1002 \subsection{kadm5_modify_principal}
1003
1004 If the named principal exists in either the Kerberos or admin
1005 principal database, but not both, return KADM5_BAD_DB.
1006
1007 If pw_history_num changes and the new value $n$ is smaller than the
1008 current value of num_old_keys, old_keys should end up with the $n$
1009 most recent keys; these are found by counting backwards $n$ elements
1010 in old_keys from old_key_next.  old_key_nexts should then be reset to
1011 0, the oldest of the saved keys, and num_old_keys set to $n$, the
1012 new actual number of old keys in the array.  
1013
1014 \subsection{kadm5_chpass_principal, randkey_principal}
1015
1016 The algorithm for determining whether a password is in the principal's
1017 key history is complicated by the use of the kadmin/history \k{h}
1018 encrypting key.  
1019
1020 \begin{enumerate}
1021 \item For kadm5_chpass_principal, convert the password to a key
1022 using string-to-key and the salt method specified by the command line
1023 arguments.
1024
1025 \item If the POLICY bit is set and pw_history_num is not zero, check
1026 if the new key is in the history.
1027 \begin{enumerate}
1028 \item Retrieve the principal's current key and decrypt it with \k{M}.
1029 If it is the same as the new key, return KADM5_PASS_REUSE.
1030 \item Retrieve the kadmin/history key \k{h} and decrypt it with \k{M}.
1031 \item Encrypt the principal's new key in \k{h}.
1032 \item If the principal's new key encrypted in \k{h} is in old_keys,
1033 return KADM5_PASS_REUSE.
1034 \item Encrypt the principal's current key in \k{h} and store it in
1035 old_keys.
1036 \item Erase the memory containing \k{h}.
1037 \end{enumerate}
1038
1039 \item Encrypt the principal's new key in \k{M} and store it in the
1040 database.
1041 \item Erase the memory containing \k{M}.
1042 \end{enumerate}
1043
1044 To store the an encrypted key in old_keys, insert it as the
1045 old_key_next element of old_keys, and increment old_key_next by one
1046 modulo pw_history_num.
1047
1048 \subsection{kadm5_get_principal}
1049
1050 If the named principal exists in either the Kerberos or admin
1051 principal database, but not both, return KADM5_BAD_DB.
1052
1053 \end{document}