Commit df251b1c38e43f43f3cb4cb49b131a975464521e
0 parents
initial checkin / version
Showing
4 changed files
with
2061 additions
and
0 deletions
LICENSE.txt
0 → 100644
1 | +++ a/LICENSE.txt | |
1 | + GNU GENERAL PUBLIC LICENSE | |
2 | + Version 3, 29 June 2007 | |
3 | + | |
4 | + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> | |
5 | + Everyone is permitted to copy and distribute verbatim copies | |
6 | + of this license document, but changing it is not allowed. | |
7 | + | |
8 | + Preamble | |
9 | + | |
10 | + The GNU General Public License is a free, copyleft license for | |
11 | +software and other kinds of works. | |
12 | + | |
13 | + The licenses for most software and other practical works are designed | |
14 | +to take away your freedom to share and change the works. By contrast, | |
15 | +the GNU General Public License is intended to guarantee your freedom to | |
16 | +share and change all versions of a program--to make sure it remains free | |
17 | +software for all its users. We, the Free Software Foundation, use the | |
18 | +GNU General Public License for most of our software; it applies also to | |
19 | +any other work released this way by its authors. You can apply it to | |
20 | +your programs, too. | |
21 | + | |
22 | + When we speak of free software, we are referring to freedom, not | |
23 | +price. Our General Public Licenses are designed to make sure that you | |
24 | +have the freedom to distribute copies of free software (and charge for | |
25 | +them if you wish), that you receive source code or can get it if you | |
26 | +want it, that you can change the software or use pieces of it in new | |
27 | +free programs, and that you know you can do these things. | |
28 | + | |
29 | + To protect your rights, we need to prevent others from denying you | |
30 | +these rights or asking you to surrender the rights. Therefore, you have | |
31 | +certain responsibilities if you distribute copies of the software, or if | |
32 | +you modify it: responsibilities to respect the freedom of others. | |
33 | + | |
34 | + For example, if you distribute copies of such a program, whether | |
35 | +gratis or for a fee, you must pass on to the recipients the same | |
36 | +freedoms that you received. You must make sure that they, too, receive | |
37 | +or can get the source code. And you must show them these terms so they | |
38 | +know their rights. | |
39 | + | |
40 | + Developers that use the GNU GPL protect your rights with two steps: | |
41 | +(1) assert copyright on the software, and (2) offer you this License | |
42 | +giving you legal permission to copy, distribute and/or modify it. | |
43 | + | |
44 | + For the developers' and authors' protection, the GPL clearly explains | |
45 | +that there is no warranty for this free software. For both users' and | |
46 | +authors' sake, the GPL requires that modified versions be marked as | |
47 | +changed, so that their problems will not be attributed erroneously to | |
48 | +authors of previous versions. | |
49 | + | |
50 | + Some devices are designed to deny users access to install or run | |
51 | +modified versions of the software inside them, although the manufacturer | |
52 | +can do so. This is fundamentally incompatible with the aim of | |
53 | +protecting users' freedom to change the software. The systematic | |
54 | +pattern of such abuse occurs in the area of products for individuals to | |
55 | +use, which is precisely where it is most unacceptable. Therefore, we | |
56 | +have designed this version of the GPL to prohibit the practice for those | |
57 | +products. If such problems arise substantially in other domains, we | |
58 | +stand ready to extend this provision to those domains in future versions | |
59 | +of the GPL, as needed to protect the freedom of users. | |
60 | + | |
61 | + Finally, every program is threatened constantly by software patents. | |
62 | +States should not allow patents to restrict development and use of | |
63 | +software on general-purpose computers, but in those that do, we wish to | |
64 | +avoid the special danger that patents applied to a free program could | |
65 | +make it effectively proprietary. To prevent this, the GPL assures that | |
66 | +patents cannot be used to render the program non-free. | |
67 | + | |
68 | + The precise terms and conditions for copying, distribution and | |
69 | +modification follow. | |
70 | + | |
71 | + TERMS AND CONDITIONS | |
72 | + | |
73 | + 0. Definitions. | |
74 | + | |
75 | + "This License" refers to version 3 of the GNU General Public License. | |
76 | + | |
77 | + "Copyright" also means copyright-like laws that apply to other kinds of | |
78 | +works, such as semiconductor masks. | |
79 | + | |
80 | + "The Program" refers to any copyrightable work licensed under this | |
81 | +License. Each licensee is addressed as "you". "Licensees" and | |
82 | +"recipients" may be individuals or organizations. | |
83 | + | |
84 | + To "modify" a work means to copy from or adapt all or part of the work | |
85 | +in a fashion requiring copyright permission, other than the making of an | |
86 | +exact copy. The resulting work is called a "modified version" of the | |
87 | +earlier work or a work "based on" the earlier work. | |
88 | + | |
89 | + A "covered work" means either the unmodified Program or a work based | |
90 | +on the Program. | |
91 | + | |
92 | + To "propagate" a work means to do anything with it that, without | |
93 | +permission, would make you directly or secondarily liable for | |
94 | +infringement under applicable copyright law, except executing it on a | |
95 | +computer or modifying a private copy. Propagation includes copying, | |
96 | +distribution (with or without modification), making available to the | |
97 | +public, and in some countries other activities as well. | |
98 | + | |
99 | + To "convey" a work means any kind of propagation that enables other | |
100 | +parties to make or receive copies. Mere interaction with a user through | |
101 | +a computer network, with no transfer of a copy, is not conveying. | |
102 | + | |
103 | + An interactive user interface displays "Appropriate Legal Notices" | |
104 | +to the extent that it includes a convenient and prominently visible | |
105 | +feature that (1) displays an appropriate copyright notice, and (2) | |
106 | +tells the user that there is no warranty for the work (except to the | |
107 | +extent that warranties are provided), that licensees may convey the | |
108 | +work under this License, and how to view a copy of this License. If | |
109 | +the interface presents a list of user commands or options, such as a | |
110 | +menu, a prominent item in the list meets this criterion. | |
111 | + | |
112 | + 1. Source Code. | |
113 | + | |
114 | + The "source code" for a work means the preferred form of the work | |
115 | +for making modifications to it. "Object code" means any non-source | |
116 | +form of a work. | |
117 | + | |
118 | + A "Standard Interface" means an interface that either is an official | |
119 | +standard defined by a recognized standards body, or, in the case of | |
120 | +interfaces specified for a particular programming language, one that | |
121 | +is widely used among developers working in that language. | |
122 | + | |
123 | + The "System Libraries" of an executable work include anything, other | |
124 | +than the work as a whole, that (a) is included in the normal form of | |
125 | +packaging a Major Component, but which is not part of that Major | |
126 | +Component, and (b) serves only to enable use of the work with that | |
127 | +Major Component, or to implement a Standard Interface for which an | |
128 | +implementation is available to the public in source code form. A | |
129 | +"Major Component", in this context, means a major essential component | |
130 | +(kernel, window system, and so on) of the specific operating system | |
131 | +(if any) on which the executable work runs, or a compiler used to | |
132 | +produce the work, or an object code interpreter used to run it. | |
133 | + | |
134 | + The "Corresponding Source" for a work in object code form means all | |
135 | +the source code needed to generate, install, and (for an executable | |
136 | +work) run the object code and to modify the work, including scripts to | |
137 | +control those activities. However, it does not include the work's | |
138 | +System Libraries, or general-purpose tools or generally available free | |
139 | +programs which are used unmodified in performing those activities but | |
140 | +which are not part of the work. For example, Corresponding Source | |
141 | +includes interface definition files associated with source files for | |
142 | +the work, and the source code for shared libraries and dynamically | |
143 | +linked subprograms that the work is specifically designed to require, | |
144 | +such as by intimate data communication or control flow between those | |
145 | +subprograms and other parts of the work. | |
146 | + | |
147 | + The Corresponding Source need not include anything that users | |
148 | +can regenerate automatically from other parts of the Corresponding | |
149 | +Source. | |
150 | + | |
151 | + The Corresponding Source for a work in source code form is that | |
152 | +same work. | |
153 | + | |
154 | + 2. Basic Permissions. | |
155 | + | |
156 | + All rights granted under this License are granted for the term of | |
157 | +copyright on the Program, and are irrevocable provided the stated | |
158 | +conditions are met. This License explicitly affirms your unlimited | |
159 | +permission to run the unmodified Program. The output from running a | |
160 | +covered work is covered by this License only if the output, given its | |
161 | +content, constitutes a covered work. This License acknowledges your | |
162 | +rights of fair use or other equivalent, as provided by copyright law. | |
163 | + | |
164 | + You may make, run and propagate covered works that you do not | |
165 | +convey, without conditions so long as your license otherwise remains | |
166 | +in force. You may convey covered works to others for the sole purpose | |
167 | +of having them make modifications exclusively for you, or provide you | |
168 | +with facilities for running those works, provided that you comply with | |
169 | +the terms of this License in conveying all material for which you do | |
170 | +not control copyright. Those thus making or running the covered works | |
171 | +for you must do so exclusively on your behalf, under your direction | |
172 | +and control, on terms that prohibit them from making any copies of | |
173 | +your copyrighted material outside their relationship with you. | |
174 | + | |
175 | + Conveying under any other circumstances is permitted solely under | |
176 | +the conditions stated below. Sublicensing is not allowed; section 10 | |
177 | +makes it unnecessary. | |
178 | + | |
179 | + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. | |
180 | + | |
181 | + No covered work shall be deemed part of an effective technological | |
182 | +measure under any applicable law fulfilling obligations under article | |
183 | +11 of the WIPO copyright treaty adopted on 20 December 1996, or | |
184 | +similar laws prohibiting or restricting circumvention of such | |
185 | +measures. | |
186 | + | |
187 | + When you convey a covered work, you waive any legal power to forbid | |
188 | +circumvention of technological measures to the extent such circumvention | |
189 | +is effected by exercising rights under this License with respect to | |
190 | +the covered work, and you disclaim any intention to limit operation or | |
191 | +modification of the work as a means of enforcing, against the work's | |
192 | +users, your or third parties' legal rights to forbid circumvention of | |
193 | +technological measures. | |
194 | + | |
195 | + 4. Conveying Verbatim Copies. | |
196 | + | |
197 | + You may convey verbatim copies of the Program's source code as you | |
198 | +receive it, in any medium, provided that you conspicuously and | |
199 | +appropriately publish on each copy an appropriate copyright notice; | |
200 | +keep intact all notices stating that this License and any | |
201 | +non-permissive terms added in accord with section 7 apply to the code; | |
202 | +keep intact all notices of the absence of any warranty; and give all | |
203 | +recipients a copy of this License along with the Program. | |
204 | + | |
205 | + You may charge any price or no price for each copy that you convey, | |
206 | +and you may offer support or warranty protection for a fee. | |
207 | + | |
208 | + 5. Conveying Modified Source Versions. | |
209 | + | |
210 | + You may convey a work based on the Program, or the modifications to | |
211 | +produce it from the Program, in the form of source code under the | |
212 | +terms of section 4, provided that you also meet all of these conditions: | |
213 | + | |
214 | + a) The work must carry prominent notices stating that you modified | |
215 | + it, and giving a relevant date. | |
216 | + | |
217 | + b) The work must carry prominent notices stating that it is | |
218 | + released under this License and any conditions added under section | |
219 | + 7. This requirement modifies the requirement in section 4 to | |
220 | + "keep intact all notices". | |
221 | + | |
222 | + c) You must license the entire work, as a whole, under this | |
223 | + License to anyone who comes into possession of a copy. This | |
224 | + License will therefore apply, along with any applicable section 7 | |
225 | + additional terms, to the whole of the work, and all its parts, | |
226 | + regardless of how they are packaged. This License gives no | |
227 | + permission to license the work in any other way, but it does not | |
228 | + invalidate such permission if you have separately received it. | |
229 | + | |
230 | + d) If the work has interactive user interfaces, each must display | |
231 | + Appropriate Legal Notices; however, if the Program has interactive | |
232 | + interfaces that do not display Appropriate Legal Notices, your | |
233 | + work need not make them do so. | |
234 | + | |
235 | + A compilation of a covered work with other separate and independent | |
236 | +works, which are not by their nature extensions of the covered work, | |
237 | +and which are not combined with it such as to form a larger program, | |
238 | +in or on a volume of a storage or distribution medium, is called an | |
239 | +"aggregate" if the compilation and its resulting copyright are not | |
240 | +used to limit the access or legal rights of the compilation's users | |
241 | +beyond what the individual works permit. Inclusion of a covered work | |
242 | +in an aggregate does not cause this License to apply to the other | |
243 | +parts of the aggregate. | |
244 | + | |
245 | + 6. Conveying Non-Source Forms. | |
246 | + | |
247 | + You may convey a covered work in object code form under the terms | |
248 | +of sections 4 and 5, provided that you also convey the | |
249 | +machine-readable Corresponding Source under the terms of this License, | |
250 | +in one of these ways: | |
251 | + | |
252 | + a) Convey the object code in, or embodied in, a physical product | |
253 | + (including a physical distribution medium), accompanied by the | |
254 | + Corresponding Source fixed on a durable physical medium | |
255 | + customarily used for software interchange. | |
256 | + | |
257 | + b) Convey the object code in, or embodied in, a physical product | |
258 | + (including a physical distribution medium), accompanied by a | |
259 | + written offer, valid for at least three years and valid for as | |
260 | + long as you offer spare parts or customer support for that product | |
261 | + model, to give anyone who possesses the object code either (1) a | |
262 | + copy of the Corresponding Source for all the software in the | |
263 | + product that is covered by this License, on a durable physical | |
264 | + medium customarily used for software interchange, for a price no | |
265 | + more than your reasonable cost of physically performing this | |
266 | + conveying of source, or (2) access to copy the | |
267 | + Corresponding Source from a network server at no charge. | |
268 | + | |
269 | + c) Convey individual copies of the object code with a copy of the | |
270 | + written offer to provide the Corresponding Source. This | |
271 | + alternative is allowed only occasionally and noncommercially, and | |
272 | + only if you received the object code with such an offer, in accord | |
273 | + with subsection 6b. | |
274 | + | |
275 | + d) Convey the object code by offering access from a designated | |
276 | + place (gratis or for a charge), and offer equivalent access to the | |
277 | + Corresponding Source in the same way through the same place at no | |
278 | + further charge. You need not require recipients to copy the | |
279 | + Corresponding Source along with the object code. If the place to | |
280 | + copy the object code is a network server, the Corresponding Source | |
281 | + may be on a different server (operated by you or a third party) | |
282 | + that supports equivalent copying facilities, provided you maintain | |
283 | + clear directions next to the object code saying where to find the | |
284 | + Corresponding Source. Regardless of what server hosts the | |
285 | + Corresponding Source, you remain obligated to ensure that it is | |
286 | + available for as long as needed to satisfy these requirements. | |
287 | + | |
288 | + e) Convey the object code using peer-to-peer transmission, provided | |
289 | + you inform other peers where the object code and Corresponding | |
290 | + Source of the work are being offered to the general public at no | |
291 | + charge under subsection 6d. | |
292 | + | |
293 | + A separable portion of the object code, whose source code is excluded | |
294 | +from the Corresponding Source as a System Library, need not be | |
295 | +included in conveying the object code work. | |
296 | + | |
297 | + A "User Product" is either (1) a "consumer product", which means any | |
298 | +tangible personal property which is normally used for personal, family, | |
299 | +or household purposes, or (2) anything designed or sold for incorporation | |
300 | +into a dwelling. In determining whether a product is a consumer product, | |
301 | +doubtful cases shall be resolved in favor of coverage. For a particular | |
302 | +product received by a particular user, "normally used" refers to a | |
303 | +typical or common use of that class of product, regardless of the status | |
304 | +of the particular user or of the way in which the particular user | |
305 | +actually uses, or expects or is expected to use, the product. A product | |
306 | +is a consumer product regardless of whether the product has substantial | |
307 | +commercial, industrial or non-consumer uses, unless such uses represent | |
308 | +the only significant mode of use of the product. | |
309 | + | |
310 | + "Installation Information" for a User Product means any methods, | |
311 | +procedures, authorization keys, or other information required to install | |
312 | +and execute modified versions of a covered work in that User Product from | |
313 | +a modified version of its Corresponding Source. The information must | |
314 | +suffice to ensure that the continued functioning of the modified object | |
315 | +code is in no case prevented or interfered with solely because | |
316 | +modification has been made. | |
317 | + | |
318 | + If you convey an object code work under this section in, or with, or | |
319 | +specifically for use in, a User Product, and the conveying occurs as | |
320 | +part of a transaction in which the right of possession and use of the | |
321 | +User Product is transferred to the recipient in perpetuity or for a | |
322 | +fixed term (regardless of how the transaction is characterized), the | |
323 | +Corresponding Source conveyed under this section must be accompanied | |
324 | +by the Installation Information. But this requirement does not apply | |
325 | +if neither you nor any third party retains the ability to install | |
326 | +modified object code on the User Product (for example, the work has | |
327 | +been installed in ROM). | |
328 | + | |
329 | + The requirement to provide Installation Information does not include a | |
330 | +requirement to continue to provide support service, warranty, or updates | |
331 | +for a work that has been modified or installed by the recipient, or for | |
332 | +the User Product in which it has been modified or installed. Access to a | |
333 | +network may be denied when the modification itself materially and | |
334 | +adversely affects the operation of the network or violates the rules and | |
335 | +protocols for communication across the network. | |
336 | + | |
337 | + Corresponding Source conveyed, and Installation Information provided, | |
338 | +in accord with this section must be in a format that is publicly | |
339 | +documented (and with an implementation available to the public in | |
340 | +source code form), and must require no special password or key for | |
341 | +unpacking, reading or copying. | |
342 | + | |
343 | + 7. Additional Terms. | |
344 | + | |
345 | + "Additional permissions" are terms that supplement the terms of this | |
346 | +License by making exceptions from one or more of its conditions. | |
347 | +Additional permissions that are applicable to the entire Program shall | |
348 | +be treated as though they were included in this License, to the extent | |
349 | +that they are valid under applicable law. If additional permissions | |
350 | +apply only to part of the Program, that part may be used separately | |
351 | +under those permissions, but the entire Program remains governed by | |
352 | +this License without regard to the additional permissions. | |
353 | + | |
354 | + When you convey a copy of a covered work, you may at your option | |
355 | +remove any additional permissions from that copy, or from any part of | |
356 | +it. (Additional permissions may be written to require their own | |
357 | +removal in certain cases when you modify the work.) You may place | |
358 | +additional permissions on material, added by you to a covered work, | |
359 | +for which you have or can give appropriate copyright permission. | |
360 | + | |
361 | + Notwithstanding any other provision of this License, for material you | |
362 | +add to a covered work, you may (if authorized by the copyright holders of | |
363 | +that material) supplement the terms of this License with terms: | |
364 | + | |
365 | + a) Disclaiming warranty or limiting liability differently from the | |
366 | + terms of sections 15 and 16 of this License; or | |
367 | + | |
368 | + b) Requiring preservation of specified reasonable legal notices or | |
369 | + author attributions in that material or in the Appropriate Legal | |
370 | + Notices displayed by works containing it; or | |
371 | + | |
372 | + c) Prohibiting misrepresentation of the origin of that material, or | |
373 | + requiring that modified versions of such material be marked in | |
374 | + reasonable ways as different from the original version; or | |
375 | + | |
376 | + d) Limiting the use for publicity purposes of names of licensors or | |
377 | + authors of the material; or | |
378 | + | |
379 | + e) Declining to grant rights under trademark law for use of some | |
380 | + trade names, trademarks, or service marks; or | |
381 | + | |
382 | + f) Requiring indemnification of licensors and authors of that | |
383 | + material by anyone who conveys the material (or modified versions of | |
384 | + it) with contractual assumptions of liability to the recipient, for | |
385 | + any liability that these contractual assumptions directly impose on | |
386 | + those licensors and authors. | |
387 | + | |
388 | + All other non-permissive additional terms are considered "further | |
389 | +restrictions" within the meaning of section 10. If the Program as you | |
390 | +received it, or any part of it, contains a notice stating that it is | |
391 | +governed by this License along with a term that is a further | |
392 | +restriction, you may remove that term. If a license document contains | |
393 | +a further restriction but permits relicensing or conveying under this | |
394 | +License, you may add to a covered work material governed by the terms | |
395 | +of that license document, provided that the further restriction does | |
396 | +not survive such relicensing or conveying. | |
397 | + | |
398 | + If you add terms to a covered work in accord with this section, you | |
399 | +must place, in the relevant source files, a statement of the | |
400 | +additional terms that apply to those files, or a notice indicating | |
401 | +where to find the applicable terms. | |
402 | + | |
403 | + Additional terms, permissive or non-permissive, may be stated in the | |
404 | +form of a separately written license, or stated as exceptions; | |
405 | +the above requirements apply either way. | |
406 | + | |
407 | + 8. Termination. | |
408 | + | |
409 | + You may not propagate or modify a covered work except as expressly | |
410 | +provided under this License. Any attempt otherwise to propagate or | |
411 | +modify it is void, and will automatically terminate your rights under | |
412 | +this License (including any patent licenses granted under the third | |
413 | +paragraph of section 11). | |
414 | + | |
415 | + However, if you cease all violation of this License, then your | |
416 | +license from a particular copyright holder is reinstated (a) | |
417 | +provisionally, unless and until the copyright holder explicitly and | |
418 | +finally terminates your license, and (b) permanently, if the copyright | |
419 | +holder fails to notify you of the violation by some reasonable means | |
420 | +prior to 60 days after the cessation. | |
421 | + | |
422 | + Moreover, your license from a particular copyright holder is | |
423 | +reinstated permanently if the copyright holder notifies you of the | |
424 | +violation by some reasonable means, this is the first time you have | |
425 | +received notice of violation of this License (for any work) from that | |
426 | +copyright holder, and you cure the violation prior to 30 days after | |
427 | +your receipt of the notice. | |
428 | + | |
429 | + Termination of your rights under this section does not terminate the | |
430 | +licenses of parties who have received copies or rights from you under | |
431 | +this License. If your rights have been terminated and not permanently | |
432 | +reinstated, you do not qualify to receive new licenses for the same | |
433 | +material under section 10. | |
434 | + | |
435 | + 9. Acceptance Not Required for Having Copies. | |
436 | + | |
437 | + You are not required to accept this License in order to receive or | |
438 | +run a copy of the Program. Ancillary propagation of a covered work | |
439 | +occurring solely as a consequence of using peer-to-peer transmission | |
440 | +to receive a copy likewise does not require acceptance. However, | |
441 | +nothing other than this License grants you permission to propagate or | |
442 | +modify any covered work. These actions infringe copyright if you do | |
443 | +not accept this License. Therefore, by modifying or propagating a | |
444 | +covered work, you indicate your acceptance of this License to do so. | |
445 | + | |
446 | + 10. Automatic Licensing of Downstream Recipients. | |
447 | + | |
448 | + Each time you convey a covered work, the recipient automatically | |
449 | +receives a license from the original licensors, to run, modify and | |
450 | +propagate that work, subject to this License. You are not responsible | |
451 | +for enforcing compliance by third parties with this License. | |
452 | + | |
453 | + An "entity transaction" is a transaction transferring control of an | |
454 | +organization, or substantially all assets of one, or subdividing an | |
455 | +organization, or merging organizations. If propagation of a covered | |
456 | +work results from an entity transaction, each party to that | |
457 | +transaction who receives a copy of the work also receives whatever | |
458 | +licenses to the work the party's predecessor in interest had or could | |
459 | +give under the previous paragraph, plus a right to possession of the | |
460 | +Corresponding Source of the work from the predecessor in interest, if | |
461 | +the predecessor has it or can get it with reasonable efforts. | |
462 | + | |
463 | + You may not impose any further restrictions on the exercise of the | |
464 | +rights granted or affirmed under this License. For example, you may | |
465 | +not impose a license fee, royalty, or other charge for exercise of | |
466 | +rights granted under this License, and you may not initiate litigation | |
467 | +(including a cross-claim or counterclaim in a lawsuit) alleging that | |
468 | +any patent claim is infringed by making, using, selling, offering for | |
469 | +sale, or importing the Program or any portion of it. | |
470 | + | |
471 | + 11. Patents. | |
472 | + | |
473 | + A "contributor" is a copyright holder who authorizes use under this | |
474 | +License of the Program or a work on which the Program is based. The | |
475 | +work thus licensed is called the contributor's "contributor version". | |
476 | + | |
477 | + A contributor's "essential patent claims" are all patent claims | |
478 | +owned or controlled by the contributor, whether already acquired or | |
479 | +hereafter acquired, that would be infringed by some manner, permitted | |
480 | +by this License, of making, using, or selling its contributor version, | |
481 | +but do not include claims that would be infringed only as a | |
482 | +consequence of further modification of the contributor version. For | |
483 | +purposes of this definition, "control" includes the right to grant | |
484 | +patent sublicenses in a manner consistent with the requirements of | |
485 | +this License. | |
486 | + | |
487 | + Each contributor grants you a non-exclusive, worldwide, royalty-free | |
488 | +patent license under the contributor's essential patent claims, to | |
489 | +make, use, sell, offer for sale, import and otherwise run, modify and | |
490 | +propagate the contents of its contributor version. | |
491 | + | |
492 | + In the following three paragraphs, a "patent license" is any express | |
493 | +agreement or commitment, however denominated, not to enforce a patent | |
494 | +(such as an express permission to practice a patent or covenant not to | |
495 | +sue for patent infringement). To "grant" such a patent license to a | |
496 | +party means to make such an agreement or commitment not to enforce a | |
497 | +patent against the party. | |
498 | + | |
499 | + If you convey a covered work, knowingly relying on a patent license, | |
500 | +and the Corresponding Source of the work is not available for anyone | |
501 | +to copy, free of charge and under the terms of this License, through a | |
502 | +publicly available network server or other readily accessible means, | |
503 | +then you must either (1) cause the Corresponding Source to be so | |
504 | +available, or (2) arrange to deprive yourself of the benefit of the | |
505 | +patent license for this particular work, or (3) arrange, in a manner | |
506 | +consistent with the requirements of this License, to extend the patent | |
507 | +license to downstream recipients. "Knowingly relying" means you have | |
508 | +actual knowledge that, but for the patent license, your conveying the | |
509 | +covered work in a country, or your recipient's use of the covered work | |
510 | +in a country, would infringe one or more identifiable patents in that | |
511 | +country that you have reason to believe are valid. | |
512 | + | |
513 | + If, pursuant to or in connection with a single transaction or | |
514 | +arrangement, you convey, or propagate by procuring conveyance of, a | |
515 | +covered work, and grant a patent license to some of the parties | |
516 | +receiving the covered work authorizing them to use, propagate, modify | |
517 | +or convey a specific copy of the covered work, then the patent license | |
518 | +you grant is automatically extended to all recipients of the covered | |
519 | +work and works based on it. | |
520 | + | |
521 | + A patent license is "discriminatory" if it does not include within | |
522 | +the scope of its coverage, prohibits the exercise of, or is | |
523 | +conditioned on the non-exercise of one or more of the rights that are | |
524 | +specifically granted under this License. You may not convey a covered | |
525 | +work if you are a party to an arrangement with a third party that is | |
526 | +in the business of distributing software, under which you make payment | |
527 | +to the third party based on the extent of your activity of conveying | |
528 | +the work, and under which the third party grants, to any of the | |
529 | +parties who would receive the covered work from you, a discriminatory | |
530 | +patent license (a) in connection with copies of the covered work | |
531 | +conveyed by you (or copies made from those copies), or (b) primarily | |
532 | +for and in connection with specific products or compilations that | |
533 | +contain the covered work, unless you entered into that arrangement, | |
534 | +or that patent license was granted, prior to 28 March 2007. | |
535 | + | |
536 | + Nothing in this License shall be construed as excluding or limiting | |
537 | +any implied license or other defenses to infringement that may | |
538 | +otherwise be available to you under applicable patent law. | |
539 | + | |
540 | + 12. No Surrender of Others' Freedom. | |
541 | + | |
542 | + If conditions are imposed on you (whether by court order, agreement or | |
543 | +otherwise) that contradict the conditions of this License, they do not | |
544 | +excuse you from the conditions of this License. If you cannot convey a | |
545 | +covered work so as to satisfy simultaneously your obligations under this | |
546 | +License and any other pertinent obligations, then as a consequence you may | |
547 | +not convey it at all. For example, if you agree to terms that obligate you | |
548 | +to collect a royalty for further conveying from those to whom you convey | |
549 | +the Program, the only way you could satisfy both those terms and this | |
550 | +License would be to refrain entirely from conveying the Program. | |
551 | + | |
552 | + 13. Use with the GNU Affero General Public License. | |
553 | + | |
554 | + Notwithstanding any other provision of this License, you have | |
555 | +permission to link or combine any covered work with a work licensed | |
556 | +under version 3 of the GNU Affero General Public License into a single | |
557 | +combined work, and to convey the resulting work. The terms of this | |
558 | +License will continue to apply to the part which is the covered work, | |
559 | +but the special requirements of the GNU Affero General Public License, | |
560 | +section 13, concerning interaction through a network will apply to the | |
561 | +combination as such. | |
562 | + | |
563 | + 14. Revised Versions of this License. | |
564 | + | |
565 | + The Free Software Foundation may publish revised and/or new versions of | |
566 | +the GNU General Public License from time to time. Such new versions will | |
567 | +be similar in spirit to the present version, but may differ in detail to | |
568 | +address new problems or concerns. | |
569 | + | |
570 | + Each version is given a distinguishing version number. If the | |
571 | +Program specifies that a certain numbered version of the GNU General | |
572 | +Public License "or any later version" applies to it, you have the | |
573 | +option of following the terms and conditions either of that numbered | |
574 | +version or of any later version published by the Free Software | |
575 | +Foundation. If the Program does not specify a version number of the | |
576 | +GNU General Public License, you may choose any version ever published | |
577 | +by the Free Software Foundation. | |
578 | + | |
579 | + If the Program specifies that a proxy can decide which future | |
580 | +versions of the GNU General Public License can be used, that proxy's | |
581 | +public statement of acceptance of a version permanently authorizes you | |
582 | +to choose that version for the Program. | |
583 | + | |
584 | + Later license versions may give you additional or different | |
585 | +permissions. However, no additional obligations are imposed on any | |
586 | +author or copyright holder as a result of your choosing to follow a | |
587 | +later version. | |
588 | + | |
589 | + 15. Disclaimer of Warranty. | |
590 | + | |
591 | + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY | |
592 | +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT | |
593 | +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY | |
594 | +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, | |
595 | +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | |
596 | +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM | |
597 | +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF | |
598 | +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. | |
599 | + | |
600 | + 16. Limitation of Liability. | |
601 | + | |
602 | + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING | |
603 | +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS | |
604 | +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY | |
605 | +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE | |
606 | +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF | |
607 | +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD | |
608 | +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), | |
609 | +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF | |
610 | +SUCH DAMAGES. | |
611 | + | |
612 | + 17. Interpretation of Sections 15 and 16. | |
613 | + | |
614 | + If the disclaimer of warranty and limitation of liability provided | |
615 | +above cannot be given local legal effect according to their terms, | |
616 | +reviewing courts shall apply local law that most closely approximates | |
617 | +an absolute waiver of all civil liability in connection with the | |
618 | +Program, unless a warranty or assumption of liability accompanies a | |
619 | +copy of the Program in return for a fee. | |
620 | + | |
621 | + END OF TERMS AND CONDITIONS | |
622 | + | |
623 | + How to Apply These Terms to Your New Programs | |
624 | + | |
625 | + If you develop a new program, and you want it to be of the greatest | |
626 | +possible use to the public, the best way to achieve this is to make it | |
627 | +free software which everyone can redistribute and change under these terms. | |
628 | + | |
629 | + To do so, attach the following notices to the program. It is safest | |
630 | +to attach them to the start of each source file to most effectively | |
631 | +state the exclusion of warranty; and each file should have at least | |
632 | +the "copyright" line and a pointer to where the full notice is found. | |
633 | + | |
634 | + <one line to give the program's name and a brief idea of what it does.> | |
635 | + Copyright (C) <year> <name of author> | |
636 | + | |
637 | + This program is free software: you can redistribute it and/or modify | |
638 | + it under the terms of the GNU General Public License as published by | |
639 | + the Free Software Foundation, either version 3 of the License, or | |
640 | + (at your option) any later version. | |
641 | + | |
642 | + This program is distributed in the hope that it will be useful, | |
643 | + but WITHOUT ANY WARRANTY; without even the implied warranty of | |
644 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
645 | + GNU General Public License for more details. | |
646 | + | |
647 | + You should have received a copy of the GNU General Public License | |
648 | + along with this program. If not, see <http://www.gnu.org/licenses/>. | |
649 | + | |
650 | +Also add information on how to contact you by electronic and paper mail. | |
651 | + | |
652 | + If the program does terminal interaction, make it output a short | |
653 | +notice like this when it starts in an interactive mode: | |
654 | + | |
655 | + <program> Copyright (C) <year> <name of author> | |
656 | + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. | |
657 | + This is free software, and you are welcome to redistribute it | |
658 | + under certain conditions; type `show c' for details. | |
659 | + | |
660 | +The hypothetical commands `show w' and `show c' should show the appropriate | |
661 | +parts of the General Public License. Of course, your program's commands | |
662 | +might be different; for a GUI interface, you would use an "about box". | |
663 | + | |
664 | + You should also get your employer (if you work as a programmer) or school, | |
665 | +if any, to sign a "copyright disclaimer" for the program, if necessary. | |
666 | +For more information on this, and how to apply and follow the GNU GPL, see | |
667 | +<http://www.gnu.org/licenses/>. | |
668 | + | |
669 | + The GNU General Public License does not permit incorporating your program | |
670 | +into proprietary programs. If your program is a subroutine library, you | |
671 | +may consider it more useful to permit linking proprietary applications with | |
672 | +the library. If this is what you want to do, use the GNU Lesser General | |
673 | +Public License instead of this License. But first, please read | |
674 | +<http://www.gnu.org/philosophy/why-not-lgpl.html>. | |
... | ... |
README.md
0 → 100644
1 | +++ a/README.md | |
1 | +FreeIPA Scripts | |
2 | +=============== | |
3 | +This repository contains a small collection of scripts written to migrate my | |
4 | +existing LDAP/DNS setup (MacOS Server) to [FreeIPA](https://www.freeipa.org) | |
5 | +and manage my setup afterwards. These scripts provide functionality unavailable | |
6 | +in the FreeIPA command line tools. They use the FreeIPA API as much as possible | |
7 | +as I didn't like the provided alternatives for migration to directly update the | |
8 | +FreeIPA LDAP database. Most of these script / commands are meant to synchronize | |
9 | +between an existing situation and FreeIPA and are safe to run multiple times. | |
10 | +As side-effect, this also makes them suitable to support a gradual migration | |
11 | +over time (where a source system is still in production until final cut-over) | |
12 | + | |
13 | +The latest versions, documentation and a bug tracker are available on my | |
14 | +[GitLab instance](https://gitlab.lindenaar.net/scripts/freeipa) | |
15 | + | |
16 | +Copyright (c) 2018 Frederik Lindenaar. free for distribution under the GNU | |
17 | +General Public License, see [below](#license) | |
18 | + | |
19 | +Contents | |
20 | +======== | |
21 | +This repository contains the following scripts: | |
22 | + * [users2freeipa.py](#users2freeipa) | |
23 | + is a migration script to transfer/synchronize LDAP users to/with FreeIPA | |
24 | + * [freeipa-dns.py](#freeipadns) | |
25 | + is a script providing functionality not available in FreeIPA itself to | |
26 | + migrate/synchronize and maintain DNS zones in FreeIPA | |
27 | + | |
28 | + | |
29 | +<a name=users2freeipa>users2freeipa.py</a> | |
30 | +--------------------------------------------- | |
31 | +This script uses LDAP to obtain users from a MacOS Server (or other LDAP) | |
32 | +server and synchronizes the results with the users registered in FreeIPA. | |
33 | +Since it synchronizes data it is safe to run multiple times and users can be | |
34 | +imported also as stage users initially. | |
35 | + | |
36 | +The intent is to migrate user data and to not drag on a legacy setup. For | |
37 | +this reason, the script will create new user and group IDs and not copy homedir | |
38 | +and shell information by default. For the IDs, the legacy information can be | |
39 | +stored in an FreeIPA ID View so it remains available, other items can be copied | |
40 | +over using command line options. Passwords can be copied-over (if available in | |
41 | +a usable format), and the script also supports having FreeIPA generate random | |
42 | +passwords and store these in a file for further processing/sharing with users. | |
43 | + | |
44 | +Users can be copied from an existing (generic) LDAP database and a MacOS Server | |
45 | +OpenDirectory-flavor LDAP server. In this case, additional information (e.g. | |
46 | +Apple's generatedUID) will be copied over as well. Please note that this does | |
47 | +require customizing the FreeIPA LDAP schema, which the script will check for | |
48 | +and can install (option ```-U```). As the setup is modular it should be easy | |
49 | +to tweak or add other migrations. | |
50 | + | |
51 | +By default all users will be migrated/synchronized, but it is also possible to | |
52 | +limit this to specific user(s) or group(s) or specifically exclude specific | |
53 | +users or groups. An example to copy all users in the group ```workgroup``` | |
54 | +except ```admin``` from an Apple MacOS OpenDirectory server: | |
55 | +~~~ | |
56 | +./users2freeipa.py -v -O -U -c "Legacy LDAP" -g workgroup -x admin -G \ | |
57 | + -P -p passwords.txt ldap://ldap.mydomain.tld | |
58 | +~~~ | |
59 | +This will also install the OpenDirectory-specific schema customization, create | |
60 | +groups and copy group memberships, copy usuable passwords and ensure that all | |
61 | +users have a password (storing generated passwords to ```passwords.txt```) | |
62 | + | |
63 | +Before running a production user migration, it is important to have FreeIPA | |
64 | +setup and configured correctly so that the right defaults are used for new | |
65 | +users. Best is to start with a single user and add that as a stage user (please | |
66 | +note that this will not yet assign userIDs, group memberships and a password | |
67 | +as FreeIPA does not yet support that) and use an ID View to store legacy data. | |
68 | + | |
69 | +For all available command-line options, run ```users2freeipa.py -h``` | |
70 | + | |
71 | + | |
72 | +<a name=freeipadns>freeipa-dns.py</a> | |
73 | +---------------------------------------------------------------- | |
74 | +This script provides functionality not provided by FreeIPA to migrate and/or | |
75 | +synchronize / maintain DNS data in FreeIPA. Currently the following commands | |
76 | +are implemented: | |
77 | + * axfr - import/synchronize a DNS zone in FreeIPA using a zone-xfer. | |
78 | + for example, to migrate / synchronize fromain ```domain.tld``` from DNS | |
79 | + server ```192.168.1.53``` without checking DNS overlap, issue the command: | |
80 | + ~~~ | |
81 | + ./freeipa-dns.py -v axfr -T 172.1.2.53 -n -f none 192.168.1.53 domain.tld | |
82 | + ~~~ | |
83 | + in addition, this will ensure zone-xfers are allowed from ```172.1.2.53``` | |
84 | + and disable forwarding in FreeIPA. | |
85 | + * copy - copy a DNS record in FreeIPA within or between zones | |
86 | + for example, to copy ```A``` and ```AAAA``` from host ```wwww.domain.tld``` | |
87 | + to the domain ```domain.tld``` itself, issue the command: | |
88 | + ~~~ | |
89 | + ./freeipa-dns.py -v copy -l A AAAA wwww.domain.tld -T domain.tld | |
90 | + ~~~ | |
91 | + * move - move a DNS record in FreeIPA from one one to another | |
92 | + for example, to move ```host1.int``` in zone ```domain.tld``` to ```host``` | |
93 | + in zone ```int.domain.tld``` issue the command: | |
94 | + ~~~ | |
95 | + ./freeipa-dns.py -v move -z domain.tld host.int host.int.domain.tld | |
96 | + ~~~ | |
97 | + * serial - update (set) zone serial(s) in FreeIPA, supporting both RFC1912 | |
98 | + style serials (YYYYMMDD##) based on current date and setting the serial to | |
99 | + a specific value. To set the serial of a zone to revision 2 of today for | |
100 | + zones ```zone1.mydomain.tld``` and ```zone2.mydomain.tld```, run: | |
101 | + ~~~~ | |
102 | + ./freeipa-dns.py -v serial -t 2 zone1.mydomain.tld zone2.mydomain.tld | |
103 | + ~~~~ | |
104 | + by default this command will set the serial to a larger value (which can be | |
105 | + overridden with the ```-f```/```--force``` flag) | |
106 | + * generate - generate number-range DNS records/attributes in FreeIPA | |
107 | + This is meant to generate series of hosts or attributes, for example, to | |
108 | + generate hosts ```dhcp-01``` to ```dhcp-10``` in zone ```int.mydomain.tld``` | |
109 | + with ip addresses starting from ```192.168.2.100``` issue to command: | |
110 | + ~~~ | |
111 | + ./freeipa-dns.py -v generate int.mydomain.tld dhcp-%02d -4 192.168.2.100 \ | |
112 | + --auto-increment-a -n 5 | |
113 | + ~~~ | |
114 | + it can also be used to generate a farm of web servers in different subnets | |
115 | + with the command: | |
116 | + ~~~ | |
117 | + ./freeipa-dns.py -v generate int.mydomain.tld www -4 192.168.%d.80 -n 5 | |
118 | + ~~~ | |
119 | + * reverse-ptr - create/update reverse DNS (PTR) entries in FreeIPA | |
120 | + With this command reverse-zones can be automatically maintained. it scans | |
121 | + the zones in FreeIPA for ```A``` and ```AAAA``` records and creates the | |
122 | + corresponding records in the ```in-addr.arpa``` and ```ip6.arpa``` zones. | |
123 | + The reverse zones must exist, and can also be created with this command by: | |
124 | + ~~~ | |
125 | + ./freeipa-dns.py -v reverse-ptr -n -p -c 10. 10.100 192.168 2001:0db8:85a3 | |
126 | + ~~~ | |
127 | + which will create the reverse zones for prefixes 10.* 10.100.* 192.168.* | |
128 | + and ipv6 prefix 2001:0db8:85a3. Reverse (PTR) records will automatically be | |
129 | + created in the correct zone with the following command: | |
130 | + ~~~ | |
131 | + ./freeipa-dns.py -v reverse-ptr -a | |
132 | + ~~~ | |
133 | + by default, the command will not overwrite existing records, (which can be | |
134 | + overridden with the ```-o```/```--override``` flag). To force a PTR record | |
135 | + to point to a specific host, e.g. ```www.mydomain.tld``` run the command: | |
136 | + ~~~ | |
137 | + ./freeipa-dns.py -v reverse-ptr -o -z mydomain.tld -H www | |
138 | + ~~~ | |
139 | + | |
140 | +for available commands run ```freeipa-dns.py -h``` and to get an overview of | |
141 | +the available options for each commmand run ```freeipa-dns.py <command> -h``` | |
142 | + | |
143 | + | |
144 | +<a name="license">License</a> | |
145 | +----------------------------- | |
146 | +These scripts, documentation & configration examples are free software: you can | |
147 | +redistribute and/or modify it under the terms of the GNU General Public License | |
148 | +as published by the Free Software Foundation, either version 3 of the License, | |
149 | +or (at your option) any later version. | |
150 | + | |
151 | +This script, documenatation and configuration examples are distributed in the | |
152 | +hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied | |
153 | +warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
154 | +General Public License for more details. | |
155 | + | |
156 | +You should have received a copy of the GNU General Public License along with | |
157 | +this program. If not, download it from <http://www.gnu.org/licenses/>. | |
158 | + | |
... | ... |
freeipa-dns.py
0 → 100755
1 | +++ a/freeipa-dns.py | |
1 | +#! /usr/bin/env python3 | |
2 | +# | |
3 | +# freeipa-dns.py - python script to migrate and maintain DNS domains in FreeIPA | |
4 | +# | |
5 | +# Version 1.0, latest version, documentation and bugtracker available at: | |
6 | +# https://gitlab.lindenaar.net/scripts/freeipa | |
7 | +# | |
8 | +# Copyright (c) 2018 Frederik Lindenaar | |
9 | +# | |
10 | +# This script is free software,you can redistribute and/or modify it under the | |
11 | +# terms of version 3 of the GNU General Public License as published by the Free | |
12 | +# Software Foundation, or (at your option) any later version of the license. | |
13 | +# | |
14 | +# This script is distributed in the hope that it will be useful but WITHOUT ANY | |
15 | +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR | |
16 | +# A PARTICULAR PURPOSE. See the GNU General Public License for more details. | |
17 | +# | |
18 | +# You should have received a copy of the GNU General Public License along with | |
19 | +# this program. If not, visit <http://www.gnu.org/licenses/> to download it. | |
20 | + | |
21 | +""" | |
22 | +migrate/synchronize and maintain DNS domain(s) with FreeIPA. | |
23 | + | |
24 | +This script provides functionality not provided by FreeIPA to migrate and/or | |
25 | +synchronize / maintain DNS data in FreeIPA. Currently the following commands | |
26 | +are implemented: | |
27 | + axfr import/synchronize a DNS zone in FreeIPA using a zone-xfer | |
28 | + copy copy a DNS record in FreeIPA within or between zones | |
29 | + move move a DNS record in FreeIPA from one one to another | |
30 | + serial update (set) zone serial(s) in FreeIPA | |
31 | + generate generate number-range DNS records/attributes in FreeIPA | |
32 | + reverse-ptr create/update reverse DNS (PTR) entries in FreeIPA | |
33 | + | |
34 | +for available commands run 'freeipa-dns.py -h and to get an overview of | |
35 | +the available options for each commmand run 'freeipa-dns.py <command> -h' | |
36 | +""" | |
37 | + | |
38 | +import os, logging | |
39 | +from datetime import date | |
40 | +from argparse import ArgumentParser, FileType, \ | |
41 | + _StoreAction as StoreAction, _StoreConstAction as StoreConstAction | |
42 | + | |
43 | +import dns.query | |
44 | +import dns.zone | |
45 | +from dns.rdatatype import SOA, HINFO | |
46 | +from dns.exception import DNSException | |
47 | + | |
48 | +from ipalib import api | |
49 | +from ipalib.errors import PublicError, AuthenticationError, NotFound | |
50 | + | |
51 | + | |
52 | +VERSION="1.0" | |
53 | +PROG_NAME=os.path.splitext(os.path.basename(__file__))[0] | |
54 | +PROG_VERSION=PROG_NAME + ' ' + VERSION | |
55 | +LOG_FORMAT='%(levelname)s - %(message)s' | |
56 | +LOG_FORMAT_FILE='%(asctime)s - ' + LOG_FORMAT | |
57 | + | |
58 | +logger = logging.getLogger(PROG_NAME) | |
59 | + | |
60 | + | |
61 | +##################[ Action to immediately set the log level ]################## | |
62 | +class SetLogLevel(StoreConstAction): | |
63 | + """ArgumentParser action to set log level to provided const value""" | |
64 | + def __call__(self, parser, namespace, values, option_string=None): | |
65 | + logging.getLogger(PROG_NAME).setLevel(self.const) | |
66 | + | |
67 | +####################[ Action to immediately log to a file ]#################### | |
68 | +class SetLogFile(StoreAction): | |
69 | + """ArgumentParser action to log to file (sets up FileHandler accordingly)""" | |
70 | + def __call__(self, parser, namespace, values, option_string=None): | |
71 | + super(SetLogFile, self).__call__(parser,namespace,values,option_string) | |
72 | + formatter = logging.Formatter(LOG_FORMAT_FILE) | |
73 | + handler = logging.FileHandler(values) | |
74 | + handler.setFormatter(formatter) | |
75 | + logger = logging.getLogger(PROG_NAME) | |
76 | + logger.propagate = False | |
77 | + logger.addHandler(handler) | |
78 | + | |
79 | +def get_zone_opts(args): | |
80 | + return { | |
81 | + 'dnsttl': None if args.ttl is None else str(args.ttl), | |
82 | + 'dnsdefaultttl': None if args.default_ttl is None else str(args.default_ttl), | |
83 | + 'idnsforwardpolicy':args.forward_policy, | |
84 | + 'idnsforwarders': args.forwarder, | |
85 | + 'idnsallowquery': ';'.join(args.allow_query)+';' if args.allow_query else None, | |
86 | + 'idnsallowtransfer':';'.join(args.allow_transfer)+';' if args.allow_transfer else None, | |
87 | + 'idnsallowsyncptr': args.create_reverse_ptr, | |
88 | + }, { | |
89 | + 'skip_nameserver_check':args.no_ns_check, | |
90 | + 'skip_overlap_check': args.no_ns_check, | |
91 | + }, { | |
92 | + 'force': args.no_ns_check, | |
93 | + } | |
94 | + | |
95 | +############################[ AXFR implementation ]############################ | |
96 | +def process_zone(api, dnszone, args): | |
97 | + """Process a single DNS Zone and synchronize with FreeIPA using its API""" | |
98 | + domain = args.merge_zone if args.merge_zone else str(dnszone.origin) | |
99 | + logger.info('processing DNS domain %s to %s', str(dnszone.origin), domain) | |
100 | + soa_data = dnszone.get_rdataset(dnszone.origin, SOA)[0] | |
101 | + zone_opts, add_opts, mod_opts = get_zone_opts(args) | |
102 | + try: | |
103 | + ipa_data = api.Command.dnszone_show(domain, all=True)['result'] | |
104 | + updates = { key: str(soa_value) for key, ipa_value in ( | |
105 | + (k, v[0]) for k,v in ipa_data.items() if k.startswith('idnssoa') | |
106 | + ) for soa_value in ( getattr(soa_data, key[7:]), ) | |
107 | + if ( int(soa_value) > int(ipa_value) if key == 'idnssoaserial' | |
108 | + else str(soa_value) != str(ipa_value) ) | |
109 | + } | |
110 | + updates.update((key, value) for key,value in zone_opts.items() | |
111 | + if value is not None and not (key in ipa_data and | |
112 | + value in ipa_data[key] if isinstance(value, str) | |
113 | + else set(value).issubset(ipa_data.get(key)))) | |
114 | + if updates: | |
115 | + logger.info('updating existing domain %s in FreeIPA', domain) | |
116 | + logger.debug('updating domain %s with %s', domain, updates) | |
117 | + api.Command.dnszone_mod(domain, **mod_opts, **updates) | |
118 | + else: | |
119 | + logger.debug('no updates for existing domain %s in FreeIPA', domain) | |
120 | + except NotFound: | |
121 | + logger.info('creating new domain %s in FreeIPA', domain) | |
122 | + response = api.Command.dnszone_add(domain, **zone_opts, **add_opts, **{ | |
123 | + 'idnssoa'+key: str(getattr(soa_data, key)) for key in [ | |
124 | + 'mname','rname','serial','refresh','retry','expire','minimum']}) | |
125 | + print(response) | |
126 | + | |
127 | + api.Command.dnsrecord_del(domain, '@', | |
128 | + nsrecord=response['result']['nsrecord']) | |
129 | + | |
130 | + recordname = lambda x: dns.rdatatype.to_text(x.rdtype).lower()+'record' | |
131 | + optionchecks = tuple((key, datafield) for key, argopt, datafield in ( | |
132 | + ('force', 'no_ns_check', 'nsrecord'), | |
133 | + ('a_extra_create_reverse', 'create_reverse_ptr', 'arecord'), | |
134 | + ('aaaa_extra_create_reverse', 'create_reverse_ptr', 'aaaarecord') | |
135 | + ) if getattr(args, argopt) ) | |
136 | + options = lambda data: { k: True for k, f in optionchecks if f in data } | |
137 | + for rname, rdataset in dnszone.items(): | |
138 | + name = str(rname) | |
139 | + dns_data = { recordname(rdatas[0]): tuple(map(str, rdatas)) | |
140 | + for rdatas in rdataset.rdatasets | |
141 | + if rdatas[0].rdtype not in (SOA, HINFO) } | |
142 | + try: | |
143 | + ipa_data = api.Command.dnsrecord_show(domain, name)['result'] | |
144 | + dns_data={ key: value for key, value in dns_data.items() if not ( | |
145 | + key in ipa_data and set(value).issubset(ipa_data[key]))} | |
146 | + if dns_data: | |
147 | + logger.info('updating %s in domain %s in FreeIPA', name, domain) | |
148 | + except NotFound: | |
149 | + logger.info('adding %s to domain %s in FreeIPA', name, domain) | |
150 | + finally: | |
151 | + if dns_data: | |
152 | + dns_data.update(options(dns_data)) | |
153 | + logger.debug(dns_data) | |
154 | + api.Command.dnsrecord_add(domain, name, **dns_data) | |
155 | + else: | |
156 | + logger.debug('no updates for entry %s', name) | |
157 | + | |
158 | +def axfr(api, args): | |
159 | + for domain in args.dnszone: | |
160 | + logger.info('performing zone-xfer for domain %s', domain) | |
161 | + axfr_request = dns.query.xfr(args.dnsserver, domain, | |
162 | + source=args.source_address, relativize=args.relativize) | |
163 | + dnszone = dns.zone.from_xfr(axfr_request, relativize=args.relativize) | |
164 | + process_zone(api, dnszone, args) | |
165 | + | |
166 | + | |
167 | +############################[ COPY implementation ]############################ | |
168 | +def copy(api, args, remove=False): | |
169 | + """Copy a DNS Record in FreeIPA and optionally remove the source values""" | |
170 | + src_record, src_zone = ('@', args.source_record) if args.source_zone else \ | |
171 | + (args.source_record, args.source_zone_name) if args.source_zone_name else \ | |
172 | + args.source_record.split('.', 1) | |
173 | + dst_record, dst_zone = ('@', args.target_record) if args.target_zone else \ | |
174 | + (args.target_record, args.target_zone_name) if args.target_zone_name else \ | |
175 | + args.target_record.split('.', 1) | |
176 | + | |
177 | + logger.debug('%s %s in %s to %s in %s', 'Moving' if remove else 'Copying', | |
178 | + src_record, src_zone, dst_record, dst_zone) | |
179 | + | |
180 | + src_data = { key:value for key,value in | |
181 | + api.Command.dnsrecord_show(src_zone, src_record)['result'].items() | |
182 | + if key.endswith('record') and | |
183 | + (not args.limit_records or key[:-6].upper() in args.limit_records) } | |
184 | + logger.debug("obtained source data from %s in domain %s,%s", src_record, src_zone, src_data) | |
185 | + | |
186 | + try: | |
187 | + dst_data = api.Command.dnsrecord_show(dst_zone, dst_record)['result'] | |
188 | + if not args.merge: | |
189 | + logger.error("Destination record %s already exists in zone %s", dst_record, dst_zone) | |
190 | + exit(1) | |
191 | + updates = { key: value for key, value in src_data.items() | |
192 | + if not (key in dst_data and set(value).issubset(dst_data[key])) | |
193 | + } | |
194 | + if updates: | |
195 | + logger.info('updating %s in domain %s in FreeIPA', dst_record, dst_zone) | |
196 | + except NotFound: | |
197 | + logger.info('creating %s in domain %s in FreeIPA', dst_record, dst_zone) | |
198 | + updates = src_data | |
199 | + | |
200 | + if updates: | |
201 | + logger.debug(updates) | |
202 | + api.Command.dnsrecord_add(dst_zone, dst_record, **updates)['result'] | |
203 | + else: | |
204 | + logger.debug('no updates for entry %s in domain %s', dst_record, dst_zone) | |
205 | + | |
206 | + if remove and src_data: | |
207 | + if not args.limit_records: | |
208 | + logger.info('removing %s from domain %s in FreeIPA', src_record, src_zone) | |
209 | + api.Command.dnsrecord_delentry(src_zone, (src_record,)) | |
210 | + else: | |
211 | + logger.info('removing attributes %s from %s in domain %s in FreeIPA', | |
212 | + args.limit_records, src_record, src_zone) | |
213 | + api.Command.dnsrecord_del(src_zone, src_record, **src_data) | |
214 | + | |
215 | + | |
216 | +############################[ MOVE implementation ]############################ | |
217 | +def move(api, args): | |
218 | + """Move a DNS Record from one DNS zone in FreeIPA to another or rename it""" | |
219 | + copy(api, args, True) | |
220 | + | |
221 | + | |
222 | +###########################[ SERIAL implementation ]########################### | |
223 | +def serial(api, args, date=date.today()): | |
224 | + """Set the SOA serial number of a DNS zone to specified or RFC1912 value""" | |
225 | + serial = int(args.serial if args.serial else '%04d%02d%02d%02d'%(date.year, | |
226 | + 0 if args.year_revision is not False else date.month, | |
227 | + 0 if args.today_revision is False else date.day, | |
228 | + args.year_revision if args.year_revision else | |
229 | + args.month_revision if args.month_revision else | |
230 | + args.today_revision if args.today_revision else 0)) | |
231 | + for domain in args.dnszone: | |
232 | + ipa_serial = int( | |
233 | + api.Command.dnszone_show(domain)['result']['idnssoaserial'][0]) | |
234 | + if ipa_serial > serial and not (args.force or args.ignore_greater): | |
235 | + logger.error('current serial %s of %s is greater than target (%s)', | |
236 | + ipa_serial, domain, serial) | |
237 | + exit(1) | |
238 | + elif serial > ipa_serial or (args.force and serial != ipa_serial): | |
239 | + logger.info('updating serial of %s to %s', domain, serial) | |
240 | + api.Command.dnszone_mod(domain, idnssoaserial=serial) | |
241 | + | |
242 | + | |
243 | +##########################[ GENERATE implementation ]########################## | |
244 | +def generate(api, args): | |
245 | + """Generate DNS records / set DNS attributes based on a number range """ | |
246 | + records = { key: value for key in dir(args) if key.endswith('record') | |
247 | + for value in (getattr(args, key),) if value is not None } | |
248 | + dynamic = [k for k, v in records.items() if any(map(lambda x: '%' in x, v))] | |
249 | + autoincrement = { key: {'sep':':', 'maxvalue':65535, 'base':16, 'fmt':'%x'} | |
250 | + if key == 'aaaarecord' else {} for key in records.keys() | |
251 | + if getattr(args, 'auto_increment_'+key[:-6]) } | |
252 | + def increment(value, sep='.', maxvalue=255, base=10, fmt='%d'): | |
253 | + rest, _, value = value.rpartition(sep) | |
254 | + value = 1 if value == '' or value == 'None' else int(value, base) + 1 | |
255 | + return rest + sep + fmt % value if value < maxvalue else \ | |
256 | + increment(rest, sep, maxvalue, base, fmt) + sep + 1 | |
257 | + for number in range(args.start, args.end+1 if args.end else args.start+args.number): | |
258 | + name = args.template % number if '%' in args.template else args.template | |
259 | + if number > args.start: | |
260 | + for key, params in autoincrement.items(): | |
261 | + records[key] = list(map(lambda x: x if '%' in x else \ | |
262 | + increment(x, **params), records[key])) | |
263 | + dst_data = records.copy() | |
264 | + for key in dynamic: | |
265 | + dst_data[key] = list(map(lambda x: x%number if '%' in x else x, records[key])) | |
266 | + try: | |
267 | + ipa_data = api.Command.dnsrecord_show(args.dnszone, name)['result'] | |
268 | + updates = { key: value for key, value in dst_data.items() | |
269 | + if not (key in ipa_data and set(value).issubset(ipa_data[key]))} | |
270 | + if updates: | |
271 | + logger.info('updating %s in domain %s in FreeIPA', name, args.dnszone) | |
272 | + logger.debug(updates) | |
273 | + api.Command.dnsrecord_mod(args.dnszone, name, **updates) | |
274 | + else: | |
275 | + logger.debug('no updates for entry %s in domain %s', name, args.dnszone) | |
276 | + except NotFound: | |
277 | + logger.info('creating %s in domain %s in FreeIPA', name, args.dnszone) | |
278 | + logger.debug(updates) | |
279 | + api.Command.dnsrecord_add(args.dnszone, name, **dst_data) | |
280 | + | |
281 | + | |
282 | +#########################[ REVERSEPTR implementation ]######################### | |
283 | +def reverseptr(api, args): | |
284 | + rev_zones, ipv4_rev_zones, ipv6_rev_zones = {}, {}, {} | |
285 | + logger.info('Fetching existing reverse PTR domains') | |
286 | + for revzone in (zone for d in | |
287 | + api.Command.dnszone_find('.arpa.',pkey_only=True)['result'] | |
288 | + for zone in map(str, d['idnsname']) if zone.endswith('.arpa.')): | |
289 | + prefix, _, type = revzone[:-6].rpartition('.') | |
290 | + if type == 'ip6': | |
291 | + if not args.ipv6: | |
292 | + continue | |
293 | + reverse = lambda v: ''.join(reversed(v.replace('.',''))) | |
294 | + prefix = reverse(prefix) | |
295 | + ipv6_rev_zones[prefix] = revzone | |
296 | + else: | |
297 | + if not args.ipv4: | |
298 | + continue | |
299 | + reverse = lambda v: '.'.join(reversed(v.split('.'))) | |
300 | + prefix = reverse(prefix) + '.' | |
301 | + ipv4_rev_zones[prefix] = revzone | |
302 | + if args.dnszone or args.all_zones: | |
303 | + logger.debug('Loading reverse PTR domain %s for %s*',revzone,prefix) | |
304 | + rev_zones[prefix] = { prefix+reverse(str(ptr)): host | |
305 | + for d in api.Command.dnsrecord_find(revzone)['result'] | |
306 | + for ptr in d['idnsname'] for host in d.get('ptrrecord', ())} | |
307 | + else: | |
308 | + rev_zones[prefix] = {} | |
309 | + | |
310 | + for revprefix in args.create_revprefix: | |
311 | + try: | |
312 | + if ':' in revprefix and args.ipv6: | |
313 | + revtype = 'ipv6 ' | |
314 | + revprefix = revprefix.strip(': \t\r\n') | |
315 | + revprefix = ''.join([ '%04x' % int(w,16) | |
316 | + for w in revprefix.split(':',7) ]) | |
317 | + ipv6_rev_zones[revprefix] = revzone = \ | |
318 | + '.'.join(reversed(revprefix)) + '.ip6.arpa.' | |
319 | + elif '.' in revprefix and args.ipv4: | |
320 | + revtype = 'ipv4 ' | |
321 | + revprefix = revprefix.strip('. \t\r\n') | |
322 | + if revprefix.count('.') > 3 or any(map(lambda x: x<0 or x>255, | |
323 | + map(int, revprefix.split('.')))): | |
324 | + raise ValueError('not a valid IPv4 value') | |
325 | + revzone = '.'.join(reversed(revprefix.split('.'))) + '.in-addr.arpa.' | |
326 | + revprefix += '.' | |
327 | + ipv4_rev_zones[revprefix] = revzone | |
328 | + else: | |
329 | + revtype = '' | |
330 | + raise ValueError('unsupported reverse zone prefix') | |
331 | + except ValueError as e: | |
332 | + logger.critical('Error: %sreverse zone prefix %s is not valid: %s', | |
333 | + revtype, revprefix, e) | |
334 | + exit(1) | |
335 | + else: | |
336 | + if revprefix in rev_zones: | |
337 | + logger.debug('%sreverse zone %s exists', revtype, revprefix) | |
338 | + else: | |
339 | + logger.info('Creating %sreverse zone %s for %s*', | |
340 | + revtype, revzone, revprefix) | |
341 | + zone_opts, add_opts, _ = get_zone_opts(args) | |
342 | + api.Command.dnszone_add(revzone, **zone_opts, **add_opts) | |
343 | + rev_zones[revprefix] = {} | |
344 | + | |
345 | + revattrs = [ ('arecord', ipv4_rev_zones, sorted(ipv4_rev_zones), str, | |
346 | + lambda t,v: '.'.join(reversed(v[len(t):].split('.')))) ] if args.ipv4 else [] | |
347 | + if args.ipv6: | |
348 | + revattrs.append( ('aaaarecord', ipv6_rev_zones, sorted(ipv6_rev_zones), | |
349 | + lambda v: ''.join([ '0000' * (8-v.count(':')) if w == '' | |
350 | + else '%04x' % int(w, 16) for w in v.split(':') ]), | |
351 | + lambda t,v: '.'.join(reversed(v[len(t):]))) ) | |
352 | + excluded_zones = map(lambda x: x.strip(':.\t\r\n')+'.', args.exclude_zone) | |
353 | + for zone in (z for z in ((n for d in | |
354 | + api.Command.dnszone_find(pkey_only=True, idnszoneactive=True)['result'] | |
355 | + for n in map(str, d['idnsname'])) if args.all_zones | |
356 | + else map(lambda x: x.strip(':.\t\r\n')+'.', args.dnszone)) | |
357 | + if not (z.endswith('in-addr.arpa.') or z.endswith('ip6.arpa.') | |
358 | + or z in excluded_zones)): | |
359 | + logger.info('Processing DNS zone %s', zone) | |
360 | + for record in ( api.Command.dnsrecord_show(zone, host)['result'] | |
361 | + for host in args.host) if args.host \ | |
362 | + else api.Command.dnsrecord_find(zone)['result']: | |
363 | + recordname = str(record['idnsname'][0]) | |
364 | + recordname = zone if recordname=='@' else '%s.%s'%(recordname,zone) | |
365 | + for revattr,revzones,revzonelist,revconvert,revformat in revattrs: | |
366 | + for ipaddr in record.get(revattr, ()): | |
367 | + revaddr = revconvert(ipaddr) | |
368 | + try: | |
369 | + *oldrevs, revtarget = [ rz for rz in revzonelist | |
370 | + if revaddr.startswith(rz) ] | |
371 | + except ValueError: | |
372 | + logger.debug('Skipping %s (%s): no reverse DNS zone', | |
373 | + ipaddr, recordname) | |
374 | + else: | |
375 | + reventry = revformat(revtarget, revaddr) | |
376 | + revzone = revzones[revtarget] | |
377 | + currrev = rev_zones[revtarget].get(revaddr) | |
378 | + if currrev == recordname: | |
379 | + logger.debug('no update for %s (%s) in %s', | |
380 | + reventry, recordname, revzone) | |
381 | + elif currrev and not args.overwrite: | |
382 | + logger.warn('not updating %s (%s) in %s pointing to' | |
383 | + ' %s', reventry, recordname, revzone, currrev) | |
384 | + else: | |
385 | + action = 'modifying' if currrev else 'adding' | |
386 | + logger.info('%s %s (%s) to %s', action, reventry, | |
387 | + recordname, revzone) | |
388 | + getattr(api.Command, 'dnsrecord_%s' % action[:3])( | |
389 | + revzone, reventry, ptrrecord=recordname) | |
390 | + rev_zones[revtarget][revaddr] = recordname | |
391 | + for revzone, reventry, oldentry in ( (revzones[r], | |
392 | + revformat(r, revaddr), o) for r in oldrevs | |
393 | + for o in (rev_zones[r].get(revaddr),) if o): | |
394 | + logger.info('removing %s (%s) from %s', reventry, | |
395 | + oldentry, revzone) | |
396 | + api.Command.dnsrecord_delentry(revzone, reventry) | |
397 | + | |
398 | + | |
399 | +##########################[ Command-line processing ]########################## | |
400 | +def parse_args(): | |
401 | + """Parse command line and get parameters from environment if not set""" | |
402 | + | |
403 | + record_types = ( | |
404 | + ('A', '4', 'IPv4 address'), | |
405 | + ('AAAA', '6', 'IPv6 address'), | |
406 | + ('CNAME', 'c', 'canonical name (alias)'), | |
407 | + ('MX', 'm', 'Mail Exchange (priority + server)'), | |
408 | + ('NS', 'N', 'Nameserver name'), | |
409 | + ('PTR', 'p', 'Reverse address Pointer'), | |
410 | + ('SRV', 'V', 'Service record (priority+port+server)'), | |
411 | + ('TXT', 't', 'Text record'), | |
412 | + ('SSHFP', 'H', 'SSH Fingerprint (priority+type+fingerprint)'), | |
413 | + ) | |
414 | + parser = ArgumentParser( | |
415 | + description='Migrate or synchronize a DNS zone in FreeIPA with DNS', | |
416 | + ) | |
417 | + parser.add_argument('-V', '--version',action="version",version=PROG_VERSION) | |
418 | + | |
419 | + pgroup = parser.add_mutually_exclusive_group(required=False) | |
420 | + pgroup.add_argument('-q', '--quiet', action=SetLogLevel, const=logging.CRITICAL, | |
421 | + default=logging.CRITICAL, help='quiet (only fatal errors)') | |
422 | + pgroup.add_argument('-v', '--verbose', action=SetLogLevel, const=logging.INFO, | |
423 | + help='more verbose output') | |
424 | + pgroup.add_argument('-d', '--debug', action=SetLogLevel, const=logging.DEBUG, | |
425 | + help='debug output') | |
426 | + | |
427 | + parser.add_argument('-l', '--logfile', action=SetLogFile, | |
428 | + help='send logging output to logfile') | |
429 | + | |
430 | + zoneoptionsparser = ArgumentParser(add_help=False) | |
431 | + zoneoptionsparser.add_argument('-n', '--no-ns-check', action='store_true', | |
432 | + help='force zone/record creation in case NS not in DNS') | |
433 | + zoneoptionsparser.add_argument('-p', '--create-reverse-ptr', action='store_true', | |
434 | + help='Enable updating reverse records for created zone(s)') | |
435 | + zoneoptionsparser.add_argument('-f','--forward-policy',choices=('first','only','none'), | |
436 | + default='first', help='Set forward policy for created zone(s)') | |
437 | + zoneoptionsparser.add_argument('-F', '--forwarder', nargs="+", | |
438 | + help='Set IP addresses to forward queries for created zone(s)') | |
439 | + zoneoptionsparser.add_argument('-Q', '--allow-query', nargs="+", default=(), | |
440 | + help='Set IP addresses/ranges that can query created zone(s)') | |
441 | + zoneoptionsparser.add_argument('-T', '--allow-transfer', nargs="+", default=(), | |
442 | + help='Set IP addresses/ranges that can transfer created zone(s)') | |
443 | + zoneoptionsparser.add_argument('-t', '--ttl', type=int, | |
444 | + help='Set TTL for SOA record of created zone(s)') | |
445 | + zoneoptionsparser.add_argument('-D', '--default-ttl', type=int, | |
446 | + help='Set default TTL for records in created zone(s)') | |
447 | + | |
448 | + subparser = parser.add_subparsers(title='Available commands', dest='command') | |
449 | + subparser.required=True | |
450 | + cmdparser = subparser.add_parser('axfr', parents=[zoneoptionsparser], | |
451 | + help='import or synchronize an DNS zone in FreeIPA with the ' | |
452 | + 'result of a zone-xfer', | |
453 | + description='Migrate or synchronize a DNS zone in FreeIPA with ' | |
454 | + 'an external DNS server. Since it synchronizes data it is ' | |
455 | + 'safe to run multiple times for a domain.', | |
456 | + epilog='Please note that this uses a domain-xfer to fetch DNS ' | |
457 | + 'zone(s) so the DNS server must allow a Zone Transfer ' | |
458 | + 'for the domain from the host running the script for ' | |
459 | + 'this command to work') | |
460 | + cmdparser.set_defaults(func=axfr, cmdparser=cmdparser) | |
461 | + cmdparser.add_argument('-s', '--source-address', | |
462 | + help='perform the zone-xfr from specified address') | |
463 | + pgroup = cmdparser.add_mutually_exclusive_group(required=False) | |
464 | + pgroup.add_argument('-r', '--relativize', action='store_true', default=True, | |
465 | + help='store DNS records relative to zone origin') | |
466 | + pgroup.add_argument('-a','--absolute',action='store_false',dest='relativize', | |
467 | + help='store DNS records with absolute DNS domain') | |
468 | + | |
469 | + cmdparser.add_argument('-m', '--merge-zone', | |
470 | + help='merge DNSZONE(s) into MERGE_ZONE') | |
471 | + cmdparser.add_argument('dnsserver', help='DNS Server to request the zone from') | |
472 | + cmdparser.add_argument('dnszone', nargs='+', help='DNS Zone to synchronize') | |
473 | + | |
474 | + commonparser = ArgumentParser(add_help=False) | |
475 | + commonparser.add_argument('-m', '--merge', action='store_true', | |
476 | + help='merge SRC_RECORD into DST_RECORD (default is ' | |
477 | + 'to fail when DST_RECORD exists)') | |
478 | + commonparser.add_argument('-l', '--limit-records', nargs='+', | |
479 | + choices=list(map(lambda x:x[0], record_types)), | |
480 | + help='only move specified record types (default is to move all)') | |
481 | + pgroup = commonparser.add_mutually_exclusive_group(required=False) | |
482 | + pgroup.add_argument('-z', '--source-zone-name', | |
483 | + help='DNS zone to move SRC_RECORD from (will use SRC_RECORD if not provided)') | |
484 | + pgroup.add_argument('-Z', '--source-zone', action='store_true', | |
485 | + help='move attributes from DNS zone SRC_RECORD itself') | |
486 | + pgroup = commonparser.add_mutually_exclusive_group(required=False) | |
487 | + pgroup.add_argument('-t', '--target-zone-name', | |
488 | + help='new name for SRC_RECORD in DST_RECORD') | |
489 | + pgroup.add_argument('-T', '--target-zone', action='store_true', | |
490 | + help='move attributes from to DNS zone SRC_RECORD itself') | |
491 | + commonparser.add_argument('source_record', help='source record(s) to move') | |
492 | + commonparser.add_argument('target_record', help='DNS Zone to move records to') | |
493 | + | |
494 | + cmdparser = subparser.add_parser('copy',parents=[commonparser], | |
495 | + help='Copy a DNS record in FreeIPA within or between zones') | |
496 | + cmdparser.set_defaults(func=copy, cmdparser=cmdparser) | |
497 | + | |
498 | + cmdparser = subparser.add_parser('move',parents=[commonparser], | |
499 | + help='Move a DNS record in FreeIPA from one one to another') | |
500 | + cmdparser.set_defaults(func=move, cmdparser=cmdparser) | |
501 | + | |
502 | + cmdparser = subparser.add_parser('serial', | |
503 | + help='update (set) zone serial(s) in FreeIPA') | |
504 | + cmdparser.set_defaults(func=serial, cmdparser=cmdparser) | |
505 | + pgroup = cmdparser.add_mutually_exclusive_group(required=False) | |
506 | + pgroup.add_argument('-f', '--force', action='store_true', | |
507 | + help='force setting the SOA serial, even when smaller ' | |
508 | + '(default is to only update to larger value)') | |
509 | + pgroup.add_argument('-i', '--ignore-greater', action='store_true', | |
510 | + help='silently ignore exisging larger SOA serials ' | |
511 | + '(default is to abort if existing serial is larger)') | |
512 | + pgroup = cmdparser.add_mutually_exclusive_group(required=True) | |
513 | + generate_RFC1912 = 'generate RFC1912-format serial based on %s' | |
514 | + pgroup.add_argument('-y', '--current-year', type=int, | |
515 | + dest='year_revision', nargs='?', default=False, | |
516 | + help=generate_RFC1912 % 'current year (YYYY######)') | |
517 | + pgroup.add_argument('-m', '--current-month', type=int, | |
518 | + dest='month_revision', nargs='?', default=False, | |
519 | + help=generate_RFC1912 % 'current year & month (YYYYMM####)') | |
520 | + pgroup.add_argument('-t', '--today', type=int, | |
521 | + dest='today_revision', nargs='?', default=False, | |
522 | + help=generate_RFC1912 % 'current date (YYYYMMDD##)') | |
523 | + pgroup.add_argument('-s', '--serial', type=int, | |
524 | + help='serial value to use (must be a 32-bit integer)') | |
525 | + cmdparser.add_argument('dnszone', nargs='+', | |
526 | + help='DNS Zone to update serial for') | |
527 | + | |
528 | + cmdparser = subparser.add_parser('generate', | |
529 | + help='generate number-range DNS records/attributes in FreeIPA', | |
530 | + epilog='(*) %s/%d will be replaced with the sequence numnber, specify' | |
531 | + ' #leading zeros like with printf, i.e. %02d = 2 leading zeros') | |
532 | + cmdparser.set_defaults(func=generate, cmdparser=cmdparser) | |
533 | + cmdparser.add_argument('-s', '--start', type=int, default=1, | |
534 | + help='start (first) value of the numner range to generate, defaults to 1') | |
535 | + pgroup = cmdparser.add_mutually_exclusive_group(required=True) | |
536 | + pgroup.add_argument('-e', '--end', type=int, | |
537 | + help='end (last) value of the numner range to generate') | |
538 | + pgroup.add_argument('-n', '--number', type=int, | |
539 | + help='number of entries to generate') | |
540 | + for record, option, description in record_types: | |
541 | + cmdparser.add_argument('-'+option, '--'+record.lower()+'record', | |
542 | + nargs='+', help='set %s for record (*)' % description) | |
543 | + if option in ('4', '6'): | |
544 | + cmdparser.add_argument('--auto-increment-'+record.lower(), | |
545 | + action='store_true', help='Automatically increment %s values without a pattern' % description) | |
546 | + cmdparser.add_argument('dnszone', help='DNS Zone to generate records in') | |
547 | + cmdparser.add_argument('template', help='template for the name of the generated records (*)') | |
548 | + | |
549 | + cmdparser = subparser.add_parser('reverse-ptr', parents=[zoneoptionsparser], | |
550 | + help='create/update reverse DNS (PTR) entries in FreeIPA', | |
551 | + description='Generate IPv4/IPv6 reverse PTR zones and records.') | |
552 | + cmdparser.set_defaults(func=reverseptr, cmdparser=cmdparser) | |
553 | + pgroup = cmdparser.add_mutually_exclusive_group(required=False) | |
554 | + pgroup.add_argument('-4', '--ipv4', action='store_false', dest='ipv6', default=True, | |
555 | + help='process only ipv4 addresses') | |
556 | + pgroup.add_argument('-6', '--ipv6', action='store_false', dest='ipv4', default=True, | |
557 | + help='process only ipv6 addresses') | |
558 | + cmdparser.add_argument('-o', '--override', action='store_true', | |
559 | + help='overwrite existing reverse PTR records (default is to only add new mappings)') | |
560 | + cmdparser.add_argument('-c', '--create_revprefix', nargs='+', default=(), | |
561 | + help='create reverse zone for IPv4/IPv6 prefix ' | |
562 | + '(must contain either . or :, e.g. 10. 192.168 2001:0db8:85a3)') | |
563 | + pgroup = cmdparser.add_mutually_exclusive_group(required=False) | |
564 | + pgroup.add_argument('-a', '--all-zones', action='store_true', | |
565 | + help='process all enabled zones in FreeIPA') | |
566 | + pgroup.add_argument('-z', '--dnszone', nargs='+', default=(), | |
567 | + help='DNS zone(s) to generate reverse pointer records for') | |
568 | + cmdparser.add_argument('-H', '--host', nargs='+', | |
569 | + help='DNS host(s) to generate reverse pointer records for within each DNSZONE') | |
570 | + cmdparser.add_argument('-x', '--exclude-zone', nargs='+', default=(), | |
571 | + help='exclude specified zones') | |
572 | + | |
573 | + return parser.parse_args() | |
574 | + | |
575 | + | |
576 | +############################################################################### | |
577 | + | |
578 | +if __name__ == '__main__': | |
579 | + logging.basicConfig(format=LOG_FORMAT) | |
580 | + args = parse_args() | |
581 | + | |
582 | + try: | |
583 | + logger.debug('connecting to FreeIPA') | |
584 | + if api.isdone('finalize') is False: | |
585 | + api.bootstrap_with_global_options(context='api') | |
586 | + api.finalize() | |
587 | + api.Backend.rpcclient.connect() | |
588 | + args.func(api, args) | |
589 | + exit(0) | |
590 | + except DNSException as e: | |
591 | + logger.critical("Domain %s cannot be downloaded,%s", domain, e) | |
592 | + except AuthenticationError: | |
593 | + logger.critical("Unable to authenticate to FreeIPA, make sure you have a valid Kerberos ticket!") | |
594 | + except PublicError as e: | |
595 | + logger.critical("error while communicating with FreeIPA: %s", e) | |
596 | + exit(1) | |
597 | + | |
... | ... |
users2freeipa.py
0 → 100755
1 | +++ a/users2freeipa.py | |
1 | +#! /usr/bin/env python3 | |
2 | +# | |
3 | +# usersfreeipa.py - python script to migrate/synchronize LDAP users with FreeIPA | |
4 | +# | |
5 | +# Version 1.0, latest version, documentation and bugtracker available at: | |
6 | +# https://gitlab.lindenaar.net/scripts/freeipa | |
7 | +# | |
8 | +# Copyright (c) 2018 Frederik Lindenaar | |
9 | +# | |
10 | +# This script is free software: you can redistribute and/or modify it under the | |
11 | +# terms of version 3 of the GNU General Public License as published by the Free | |
12 | +# Software Foundation, or (at your option) any later version of the license. | |
13 | +# | |
14 | +# This script is distributed in the hope that it will be useful but WITHOUT ANY | |
15 | +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR | |
16 | +# A PARTICULAR PURPOSE. See the GNU General Public License for more details. | |
17 | +# | |
18 | +# You should have received a copy of the GNU General Public License along with | |
19 | +# this program. If not, visit <http://www.gnu.org/licenses/> to download it. | |
20 | + | |
21 | +""" | |
22 | +migrate/synchronize LDAP users with FreeIPA. | |
23 | + | |
24 | +This script uses LDAP to obtain users from a MacOS Server (or other LDAP) | |
25 | +server and synchronizes the results with the users registered in FreeIPA. | |
26 | +Since it synchronizes data it is safe to run multiple times. | |
27 | + | |
28 | +for available command-line options, run 'users2freeipa.py -h' | |
29 | +""" | |
30 | + | |
31 | +import os, logging | |
32 | +from argparse import ArgumentParser, FileType, \ | |
33 | + _StoreAction as StoreAction, _StoreConstAction as StoreConstAction | |
34 | +from base64 import b64encode | |
35 | +from getpass import getpass | |
36 | + | |
37 | +from ipalib import api | |
38 | +from ipalib.errors import PublicError, AuthenticationError, NotFound | |
39 | + | |
40 | +from ldap import LDAPError, SCOPE_SUBTREE, MOD_ADD, MOD_DELETE | |
41 | +from ldap.filter import escape_filter_chars | |
42 | +from ldap.ldapobject import LDAPObject | |
43 | +from ldap.resiter import ResultProcessor | |
44 | + | |
45 | + | |
46 | +VERSION="1.0" | |
47 | +PROG_NAME=os.path.splitext(os.path.basename(__file__))[0] | |
48 | +PROG_VERSION=PROG_NAME + ' ' + VERSION | |
49 | +LOG_FORMAT='%(levelname)s - %(message)s' | |
50 | +LOG_FORMAT_FILE='%(asctime)s - ' + LOG_FORMAT | |
51 | + | |
52 | +logger = logging.getLogger(PROG_NAME) | |
53 | + | |
54 | + | |
55 | +##################[ Action to immediately set the log level ]################## | |
56 | +class SetLogLevel(StoreConstAction): | |
57 | + """ArgumentParser action to set log level to provided const value""" | |
58 | + def __call__(self, parser, namespace, values, option_string=None): | |
59 | + logging.getLogger(PROG_NAME).setLevel(self.const) | |
60 | + | |
61 | +####################[ Action to immediately log to a file ]#################### | |
62 | +class SetLogFile(StoreAction): | |
63 | + """ArgumentParser action to log to file (sets up FileHandler accordingly)""" | |
64 | + def __call__(self, parser, namespace, values, option_string=None): | |
65 | + super(SetLogFile, self).__call__(parser,namespace,values,option_string) | |
66 | + formatter = logging.Formatter(LOG_FORMAT_FILE) | |
67 | + handler = logging.FileHandler(values) | |
68 | + handler.setFormatter(formatter) | |
69 | + logger = logging.getLogger(PROG_NAME) | |
70 | + logger.propagate = False | |
71 | + logger.addHandler(handler) | |
72 | + | |
73 | + | |
74 | +#################[ Generic LDAP Connection / ResultProcessor ]################# | |
75 | +class custom_attr(str): pass | |
76 | +class LDAPConnection(LDAPObject,ResultProcessor): | |
77 | + """LDAPConnection implements the LDAP-specifics to migrate LDAP to FreeIPA | |
78 | + | |
79 | + This class holds a generic implementation of the functionality needed to | |
80 | + migrate from a generic () LDAP server to FreeIPA. It is intended to be | |
81 | + subclassed to add the instance-specific parameters for implementation. | |
82 | + | |
83 | + Parameters and LDAP attributes steering the migration to FreeIPA are in | |
84 | + the below attributes (to be overrided by implementation subclasses): | |
85 | + | |
86 | + FreeIPA LDAP Schema customizations (used by check_schema) | |
87 | + SCHEMA_ATTRIBUTES: custom attribute mapping (oid:definiton) | |
88 | + SCHEMA_OBJECTCLASSES: custom objectclass mapping (oid:definiton) | |
89 | + | |
90 | + LDAP search parameters: | |
91 | + USER_SUBTREE: LDAP users subtree (relative to baseDN) | |
92 | + USER_OBJECTCLASS: objectclasses for searching users | |
93 | + USER_LOGINATTR: user login / (unique) key attribute | |
94 | + USER_MAPPING: mapping for LDAP attributes to FreeIPA | |
95 | + (LDAP attr: (FreeIPA attr, convert_func)) | |
96 | + GROUP_SUBTREE: LDAP groups subtree (relative to baseDN) | |
97 | + GROUP_OBJECTCLASS: objectclasses for searching group(member)s | |
98 | + GROUP_NAMEATTR: group name / (unique) key attribute | |
99 | + GROUP_DESCATTR: group description attribute | |
100 | + GROUP_GIDATTR: group gid attribute | |
101 | + GROUP_MEMBERATTR: group member attribute with member logins | |
102 | + """ | |
103 | + @staticmethod | |
104 | + def ldaplist2ipa(valuelist): return tuple(map(bytes.decode, valuelist)) | |
105 | + | |
106 | + @staticmethod | |
107 | + def ldapstr2ipa(valuelist, default=()): | |
108 | + return ' '.join(map(bytes.decode, valuelist if valuelist else default)) | |
109 | + | |
110 | + FREEIPA_SCHEMA_DN = 'cn=schema' | |
111 | + SCHEMA_ATTRIBUTES = { } | |
112 | + SCHEMA_OBJECTCLASSES = { } | |
113 | + | |
114 | + USER_OBJECTCLASS = ( 'posixAccount', 'shadowAccount' ) | |
115 | + | |
116 | + USER_SUBTREE = 'cn=users' | |
117 | + USER_LOGINATTR = 'uid' | |
118 | + USER_MAPPING = { # based on http://www.zytrax.com/books/ldap/ape/ | |
119 | + USER_LOGINATTR: (USER_LOGINATTR, ldaplist2ipa.__func__), | |
120 | + 'userPassword': ('userpassword', ldapstr2ipa.__func__), | |
121 | + 'uidNumber': ('uidnumber', ldapstr2ipa.__func__), | |
122 | + 'gidNumber': ('gidnumber', ldapstr2ipa.__func__), | |
123 | + 'gecos': ('gecos', ldapstr2ipa.__func__), | |
124 | + 'homeDirectory': ('homedirectory', ldapstr2ipa.__func__), | |
125 | + 'loginShell': ('loginshell', ldapstr2ipa.__func__), | |
126 | + 'givenName': ('givenname', ldapstr2ipa.__func__), | |
127 | + 'sn': ('sn', ldapstr2ipa.__func__), | |
128 | + 'cn': ('cn', ldapstr2ipa.__func__), | |
129 | + 'displayname': ('displayname', ldapstr2ipa.__func__), | |
130 | + 'initials': ('initials', ldapstr2ipa.__func__), | |
131 | + 'title': ('title', ldapstr2ipa.__func__), | |
132 | + 'mail': ('mail', ldaplist2ipa.__func__), | |
133 | + 'street': ('street', ldapstr2ipa.__func__), | |
134 | + 'l': ('l', ldapstr2ipa.__func__), | |
135 | + 'st': ('st', ldapstr2ipa.__func__), | |
136 | + 'postalCode': ('postalcode', ldapstr2ipa.__func__), | |
137 | + 'telephonenumber': ('telephonenumber', ldaplist2ipa.__func__), | |
138 | + 'mobile': ('mobile', ldaplist2ipa.__func__), | |
139 | + 'pager': ('pager', ldaplist2ipa.__func__), | |
140 | + 'facsimiletelephonenumber':('facsimiletelephonenumber',ldaplist2ipa.__func__), | |
141 | + 'carlicense': ('carlicense', ldaplist2ipa.__func__), | |
142 | + 'ou': ('ou', ldapstr2ipa.__func__), | |
143 | + 'departmentNumber': ('departmentnumber',ldaplist2ipa.__func__), | |
144 | + 'employeeNumber ': ('employeenumber', ldapstr2ipa.__func__), | |
145 | + 'employeeType': ('employeetype', ldapstr2ipa.__func__), | |
146 | + 'manager': ('manager', ldapstr2ipa.__func__), | |
147 | + 'userCertificate': ('usercertificate', ldaplist2ipa.__func__), | |
148 | + 'preferredLanguage':('preferredlanguage',ldapstr2ipa.__func__), | |
149 | + } | |
150 | + | |
151 | + GROUP_OBJECTCLASS = ( 'posixGroup', ) | |
152 | + GROUP_SUBTREE = 'cn=groups' | |
153 | + GROUP_NAMEATTR = 'cn' | |
154 | + GROUP_DESCATTR = GROUP_NAMEATTR | |
155 | + GROUP_GIDATTR = 'gidNumber' | |
156 | + GROUP_MEMBERATTR = 'memberUid' | |
157 | + | |
158 | + @staticmethod | |
159 | + def attrfilters(valuelist, attr, cmp='='): | |
160 | + """convert a value list into an LDAP-escaped attr=value filter list""" | |
161 | + return set(map(lambda x:attr + cmp + escape_filter_chars(x), valuelist)) | |
162 | + | |
163 | + @staticmethod | |
164 | + def filters2str(*filters, operator, default=''): | |
165 | + """convert a list of filters to a single filter(string) with operator""" | |
166 | + result = set('(%s)' % f if f[0]!='(' else f for f in filters if f) | |
167 | + return '(' + operator + ''.join(result) + ')' if len(result) > 1 else \ | |
168 | + result.pop() if result else default | |
169 | + | |
170 | + @staticmethod | |
171 | + def notfilter(fstr): | |
172 | + """Create a negative (NOT) LDAP filter based on a filter (string)""" | |
173 | + return '' if not fstr else ('(!%s)' if fstr[0]=='(' else '(!(%s))')%fstr | |
174 | + | |
175 | + def objectclassfilter(self, *objclasses, operator='|', cmp='=', default=''): | |
176 | + """Generates an LDAP filter to retrieve specific objectclass(es)""" | |
177 | + objclsfilter = self.attrfilters(objclasses, 'objectClass', cmp) | |
178 | + return self.filters2str(*objclsfilter,operator=operator,default=default) | |
179 | + | |
180 | + def usersfilter(self, *users, operator='|', cmp='=', default=''): | |
181 | + """Generates an LDAP filter to retrieve users based on login name(s)""" | |
182 | + userfilter = self.attrfilters(users,self.USER_LOGINATTR,cmp) | |
183 | + return self.filters2str(*userfilter, operator=operator, default=default) | |
184 | + | |
185 | + def groupsfilter(self, *groups, operator='|', cmp='=', default=''): | |
186 | + """Generates an LDAP filter to retrieve groups based on group name(s)""" | |
187 | + groupfilter = self.attrfilters(groups, self.GROUP_NAMEATTR, cmp) | |
188 | + return self.filters2str(*groupfilter, operator=operator, default=default) | |
189 | + | |
190 | + def groupmemberfilter(self, *members, operator='|', cmp='=', default=''): | |
191 | + """Generates an LDAP filter to retrieve groups based on their members""" | |
192 | + memberfilter = self.attrfilters(members, self.GROUP_MEMBERATTR, cmp) | |
193 | + return self.filters2str(*memberfilter,operator=operator,default=default) | |
194 | + | |
195 | + def __init__(self, server, basedn=None): | |
196 | + """Initialize connection to server, get server basedn unless provided""" | |
197 | + super(LDAPConnection, self).__init__(server) | |
198 | + self._basedn = basedn if basedn else self.get_naming_contexts()[0].decode() | |
199 | + logger.debug('Connected to %s, base_dn=%s', server, self._basedn) | |
200 | + | |
201 | + def check_schema(self, exists=True, update_schema=False): | |
202 | + """Check if schema customizations are present in the FreeIPA LDAP | |
203 | + server (or not, depending on 'exists') and apply the changes if | |
204 | + 'update_schema'. Returns whether the desired state is present. | |
205 | + """ | |
206 | + if not self.SCHEMA_ATTRIBUTES and not self.SCHEMA_OBJECTCLASSES: | |
207 | + return True | |
208 | + logger.debug('Checking LDAP schema customizations presence in FreeIPA') | |
209 | + operation = MOD_ADD if exists else MOD_DELETE | |
210 | + config = { 'attributeTypes': self.SCHEMA_ATTRIBUTES, | |
211 | + 'objectClasses': self.SCHEMA_OBJECTCLASSES } | |
212 | + ipa_ldap = LDAPObject('ldap:///') | |
213 | + ipa_schema = ipa_ldap.read_s(self.FREEIPA_SCHEMA_DN, attrlist=config.keys()) | |
214 | + updates = [ (operation, key, value) for key, cfg in config.items() | |
215 | + for cur in ({v.split(b' ')[1]: v for v in ipa_schema[key]},) | |
216 | + for value in ([ d for o,d in cfg.items() if o not in cur ] \ | |
217 | + if exists else [cur[o] for o in cfg if o in cur],) if value] | |
218 | + if updates and update_schema: | |
219 | + updates = sorted(updates, key=lambda x: x[1], reverse=not exists) | |
220 | + logger.info('%sing LDAP schema customizations in FreeIPA', | |
221 | + 'Add' if exists else 'Delet') | |
222 | + logger.debug('LDAP Schema changes: %s', updates) | |
223 | + ipa_ldap.bind_s('cn=directory manager', | |
224 | + getpass('FreeIPA diradmin password: ')) | |
225 | + ipa_ldap.modify_s(self.FREEIPA_SCHEMA_DN, updates) | |
226 | + elif updates: | |
227 | + logger.debug('Not %sing LDAP schema customizations in FreeIPA', | |
228 | + 'add' if exists else 'delet') | |
229 | + else: | |
230 | + logger.debug('LDAP schema customizations are %s in FreeIPA', | |
231 | + 'present' if exists else 'absent') | |
232 | + ipa_ldap.unbind() | |
233 | + return(not updates or update_schema) | |
234 | + | |
235 | + def search(self, base, *args, relativebase=True, **kwargs): | |
236 | + """Search using LDAPObject.search(), adding baseddn to base if needed""" | |
237 | + if relativebase and not base.endswith(self._basedn): | |
238 | + base += ',' + self._basedn | |
239 | + return super(LDAPConnection, self).search(base, *args, **kwargs) | |
240 | + | |
241 | + def get_group_members(self, *group): | |
242 | + """Returns set with users that are member of the provided group(s)""" | |
243 | + if not group: | |
244 | + return set() | |
245 | + filter=self.filters2str(self.objectclassfilter(*self.GROUP_OBJECTCLASS), | |
246 | + self.groupsfilter(*groups), operator='&') | |
247 | + logger.debug('Searching %s members with LDAP filter: %s',group,filter) | |
248 | + attrs = (self.GROUP_MEMBERATTR,) | |
249 | + msg_id = self.search(self.GROUP_SUBTREE, SCOPE_SUBTREE, filter, attrs) | |
250 | + return set(user.decode() for _,res_data,_,_ in ldap.allresults(msg_id) | |
251 | + for _, entry in res_data | |
252 | + for userlist in entry.values() | |
253 | + for user in userlist) | |
254 | + | |
255 | + def get_user_groups(self, user, groups=()): | |
256 | + """Returns list of groups that the specified user is member of. | |
257 | + checks the list of groups, if provided, or all groups | |
258 | + """ | |
259 | + filter=self.filters2str(self.objectclassfilter(*self.GROUP_OBJECTCLASS), | |
260 | + self.groupmemberfilter(user), | |
261 | + self.groupsfilter(*groups), operator='&') | |
262 | + logger.debug('Searching user\'s groups with LDAP filter: %s', filter) | |
263 | + attrs = (self.GROUP_NAMEATTR,self.GROUP_GIDATTR,self.GROUP_DESCATTR) | |
264 | + msg_id = self.search(self.GROUP_SUBTREE, SCOPE_SUBTREE, filter, attrs) | |
265 | + return [ (self.ldapstr2ipa(entry[self.GROUP_NAMEATTR]), | |
266 | + self.ldapstr2ipa(entry[self.GROUP_GIDATTR]), | |
267 | + self.ldapstr2ipa(entry.get(self.GROUP_DESCATTR, | |
268 | + entry[self.GROUP_NAMEATTR])) ) | |
269 | + for _,res_data,_,_ in ldap.allresults(msg_id) | |
270 | + for dn, entry in res_data ] | |
271 | + | |
272 | + def get_users(self, *users, excl_users=(), customfilter='', attrs=None): | |
273 | + """Returns an generator to iterate over LDAP users mapped to FreeIPA. | |
274 | + This function obtains the list of users (all if not specified) and | |
275 | + support exclusion list and custom filters for further control | |
276 | + """ | |
277 | + filter=self.filters2str(self.objectclassfilter(*self.USER_OBJECTCLASS), | |
278 | + customfilter, self.usersfilter(*users), | |
279 | + self.notfilter(self.usersfilter(*excl_users)), | |
280 | + operator='&', default='(%s=*)'%self.USER_LOGINATTR) | |
281 | + logger.debug('Searching users with LDAP filter: %s', filter) | |
282 | + msg_id = self.search(self.USER_SUBTREE, SCOPE_SUBTREE, filter, attrs) | |
283 | + for res_type,res_data,res_msgid,res_controls in self.allresults(msg_id): | |
284 | + for dn, entry in res_data: | |
285 | + if logger.getEffectiveLevel() <= logging.DEBUG: | |
286 | + notmigrated = ', '.join(key for key in entry if key not in | |
287 | + (*self.USER_MAPPING.keys(), 'objectClass')) | |
288 | + if notmigrated: | |
289 | + logger.debug('Ignoring attributes: %s', notmigrated) | |
290 | + yield (dn, { ipa_key: conv(v) for k, v in entry.items() | |
291 | + if k in self.USER_MAPPING | |
292 | + for ipa_key, conv in (self.USER_MAPPING[k],) }) | |
293 | + | |
294 | + | |
295 | + | |
296 | +##################[ MacOS LDAP Connection / ResultProcessor ]################## | |
297 | +class MacOSLDAPConnection(LDAPConnection): | |
298 | + """LDAPConnection subclass to migrate from Apple's OpenDirectory""" | |
299 | + | |
300 | + # @staticmethod | |
301 | + # def binary2ipa(valuelist): return b64encode(valuelist[0]).decode() | |
302 | + | |
303 | + SCHEMA_ATTRIBUTES = { | |
304 | + # Definition (and OID) taken from Apple MacOS Server OpenDirectory | |
305 | + b"1.3.6.1.4.1.63.1000.1.1.1.1.20": | |
306 | + b"( 1.3.6.1.4.1.63.1000.1.1.1.1.20 NAME ( 'apple-generateduid' )" | |
307 | + b" DESC 'generated unique ID' X-ORIGIN 'Apple Server OpenDirectoy'" | |
308 | + b" EQUALITY caseExactMatch SUBSTR caseExactSubstringsMatch" | |
309 | + b" SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )", | |
310 | + } | |
311 | + SCHEMA_OBJECTCLASSES = { | |
312 | + # OID: iso.org.dod.internet.private.enterprise.lindenaar.2018.8.2.1.1 | |
313 | + # https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers | |
314 | + b"1.3.6.1.4.1.18143.2018.8.2.1.1": | |
315 | + b"( 1.3.6.1.4.1.18143.2018.8.2.1.1" | |
316 | + b" NAME 'openDirectoryPerson' SUP person STRUCTURAL" | |
317 | + b" MAY ( c $ apple-generateduid ) X-ORIGIN 'Extending FreeIPA' )" | |
318 | + } | |
319 | + | |
320 | + USER_OBJECTCLASS = ( *LDAPConnection.USER_OBJECTCLASS, 'apple-user' ) | |
321 | + USER_MAPPING = { **LDAPConnection.USER_MAPPING, | |
322 | + 'objectClass': (custom_attr('objectclass'), lambda x: 'openDirectoryPerson'), | |
323 | + 'c': (custom_attr('c'), LDAPConnection.ldapstr2ipa), | |
324 | + 'apple-generateduid': (custom_attr('apple-generateduid'),LDAPConnection.ldapstr2ipa), | |
325 | + 'apple-user-homeurl': LDAPConnection.USER_MAPPING['homeDirectory'], | |
326 | + # TODO: MacOS attribute: jpegPhoto | |
327 | + # 'jpegPhoto': (custom_attr('jpegphoto'), binary2ipa.__func__), | |
328 | + # TODO: migrate MacOS Passwords (not sure this is possible) | |
329 | + } | |
330 | + | |
331 | + GROUP_OBJECTCLASS = ( *LDAPConnection.GROUP_OBJECTCLASS, 'apple-group' ) | |
332 | + GROUP_DESCATTR = 'apple-group-realname' | |
333 | + | |
334 | + | |
335 | +###########[ Generic function to get/create/update FreeIPA entries ]########### | |
336 | +def ipa_update_create(api,entity,name,*keys,get_params={},add_params={},**data): | |
337 | + """ Generic function to create or update an entity and return it. | |
338 | + This will create or update the entity, with key *key so that it reflects | |
339 | + the values provided in the mapping **data. | |
340 | + Parameters: | |
341 | + api: FreeIPA API object to use | |
342 | + entity: name of the FreeIPA entity type to create/update | |
343 | + name: textual name of the entity for logging | |
344 | + keys: the FreeIPA key for this entity (1 or more values) | |
345 | + get_params: additional parameters when retrieving the entity | |
346 | + add_params: additional parameters/values when creating the entity | |
347 | + data: mapping containing the desired values for the entity | |
348 | + Returns the updated entity | |
349 | + """ | |
350 | + try: | |
351 | + ipa_data = getattr(api.Command, '%s_show' % entity)(*keys, **get_params)['result'] | |
352 | + if data: | |
353 | + updates = { k:v for k, v in data.items() if not (k in ipa_data and v in ipa_data[k]) } | |
354 | + if updates: | |
355 | + logger.info('updating existing %s %s in FreeIPA', name, keys[-1]) | |
356 | + return getattr(api.Command, '%s_mod' % entity)(*keys, **updates)['result'] | |
357 | + else: | |
358 | + logger.debug('no updates for existing %s %s in FreeIPA', name, keys[-1]) | |
359 | + else: | |
360 | + logger.debug('found existing %s %s in FreeIPA', name, keys[-1]) | |
361 | + return ipa_data | |
362 | + except NotFound: | |
363 | + logger.info('creating new %s %s in FreeIPA', name, keys[-1]) | |
364 | + return getattr(api.Command, '%s_add' % entity)(*keys, **data, **add_params)['result'] | |
365 | + | |
366 | + | |
367 | +##########################[ Command-line processing ]########################## | |
368 | +def parse_args(): | |
369 | + """Parse command line and get parameters from environment if not set""" | |
370 | + parser = ArgumentParser( | |
371 | + description='Migrate or synchronize LDAP users with FreeIPA', | |
372 | + epilog='(*) unless specified FreeIPA defaults are used. %s is replaced ' | |
373 | + 'by the userID' | |
374 | + ) | |
375 | + parser.add_argument('-V', '--version',action="version",version=PROG_VERSION) | |
376 | + | |
377 | + pgroup = parser.add_mutually_exclusive_group(required=False) | |
378 | + pgroup.add_argument('-O', '--apple-opendirectory', action='store_const', | |
379 | + dest='ldapconnection', const=MacOSLDAPConnection, | |
380 | + default=LDAPConnection, | |
381 | + help='migrate from Apple\'s MacOS Server OpenDirectory') | |
382 | + | |
383 | + parser.add_argument('ldapserver', help='LDAP Server to request users from') | |
384 | + parser.add_argument('-b', '--basedn', help='Base DN of source LDAP server, defaults to LDAP server') | |
385 | + parser.add_argument('-u', '--user', nargs='+', default=(), | |
386 | + help='user(s) to migrate/synchronize, defaults to all') | |
387 | + parser.add_argument('-g', '--member-of', nargs='+', dest='user_group', default=(), | |
388 | + help='migrate/synchronize members of group(s)') | |
389 | + parser.add_argument('-x', '--exclude-user', nargs='+', dest='x_user', default=(), | |
390 | + help='user(s) to exclude') | |
391 | + parser.add_argument('-X', '--exclude-group', nargs='+', dest='x_group', default=(), | |
392 | + help='exclude users in specified group(s)') | |
393 | + parser.add_argument('-f', '--filter', help='additional LDAP filter to apply') | |
394 | + parser.add_argument('-G', '--migrate-groups', nargs='*', dest='group', | |
395 | + help='migrate groups+membership for specified or all groups') | |
396 | + parser.add_argument('-H', '--migrate-homedir', nargs='?', dest='homedir', default="", | |
397 | + help='Migrate (if empty) or set homedir (*)') | |
398 | + parser.add_argument('-S', '--migrate-loginshell', nargs='?', dest='loginshell', default="", | |
399 | + help='Migrate (if empty) or set login shell (*)') | |
400 | + parser.add_argument('-P', '--migrate-password', action='store_true', | |
401 | + help='migrate passwords from LDAP (if present)') | |
402 | + parser.add_argument('-p', '--enforce-passwords', dest='password_logfile', | |
403 | + help='enforce users have passwords, file generated passwords') | |
404 | + parser.add_argument('-s', '--stage', action='store_true', | |
405 | + help='create new users as staged users') | |
406 | + parser.add_argument('-c', '--compatibility-view', dest='idview', | |
407 | + help='Maintain ID Compatibility view to preserve UID/GID/homedir/shell') | |
408 | + parser.add_argument('-U', '--update-schema', action='store_true', | |
409 | + help='Configure necessary LDAP schema customizations') | |
410 | + parser.add_argument('-C', '--cleanup-schema', action='store_true', | |
411 | + help='Remove applied LDAP schema customizations and exit') | |
412 | + | |
413 | + pgroup = parser.add_mutually_exclusive_group(required=False) | |
414 | + pgroup.add_argument('-q', '--quiet', action=SetLogLevel, const=logging.CRITICAL, | |
415 | + default=logging.CRITICAL, help='quiet (only fatal errors)') | |
416 | + pgroup.add_argument('-v', '--verbose', action=SetLogLevel, const=logging.INFO, | |
417 | + help='more verbose output') | |
418 | + pgroup.add_argument('-d', '--debug', action=SetLogLevel, const=logging.DEBUG, | |
419 | + help='debug output') | |
420 | + parser.add_argument('-l', '--logfile', action=SetLogFile, | |
421 | + help='send logging output to logfile') | |
422 | + | |
423 | + return parser.parse_args() | |
424 | + | |
425 | + | |
426 | +############################[ LDAPUser processing ]############################ | |
427 | +def process_user(api, userid, user_data, stage=False, enforce_password=False): | |
428 | + """Process a single LDAP user and synchronize with FreeIPA using its API""" | |
429 | + logger.info('processing LDAP user %s', userid) | |
430 | + | |
431 | + try: | |
432 | + ipa_data = api.Command.user_show(userid, all=True)['result'] | |
433 | + logger.debug('found active user %s', userid) | |
434 | + stage = False | |
435 | + except NotFound: | |
436 | + try: | |
437 | + ipa_data = api.Command.stageuser_show(userid, all=True)['result'] | |
438 | + if stage: | |
439 | + logger.debug('found existing stage entry for user %s', userid) | |
440 | + else: | |
441 | + logger.info('activating stage user %s', userid) | |
442 | + api.Command.stageuser_activate(userid) | |
443 | + except NotFound: | |
444 | + ipa_data = { } | |
445 | + | |
446 | + what = 'stageuser' if stage else 'user' | |
447 | + updates = user_data if not ipa_data else { key: value | |
448 | + for key, value in user_data.items() if not (key in ipa_data and | |
449 | + value in ipa_data[key] if isinstance(value, str) | |
450 | + else set(value).issubset(ipa_data[key])) } | |
451 | + | |
452 | + if ipa_data.get('has_password') and 'userpassword' in updates: | |
453 | + logger.debug('Not replacing existing password for %s %s', what, userid) | |
454 | + del updates['userpassword'] | |
455 | + elif enforce_password and not (stage or ipa_data.get('has_password')): | |
456 | + logger.info('Enforcing password for user %s in FreeIPA', userid) | |
457 | + updates['random'] = True | |
458 | + | |
459 | + if updates or not ipa_data: | |
460 | + action = 'Upd' if ipa_data else 'Cre' | |
461 | + logger.info('%sating %s %s in FreeIPA', action, what, userid) | |
462 | + logger.debug('%sating %s %s with %s', action, what, userid, updates) | |
463 | + cust=[k+'='+v for k,v in updates.items() if isinstance(k, custom_attr)] | |
464 | + if cust: | |
465 | + updates = { 'addattr': cust if ipa_data else None, **{ k:v | |
466 | + for k,v in updates.items() if not isinstance(k, custom_attr) }} | |
467 | + command = getattr(api.Command, what + ('_mod' if ipa_data else '_add')) | |
468 | + ipa_data = command(userid, **updates)['result'] | |
469 | + if cust and action == 'Cre': | |
470 | + getattr(api.Command, what + '_mod')(userid, addattr=cust) | |
471 | + else: | |
472 | + logger.debug('no updates for %s %s in FreeIPA', what, userid) | |
473 | + | |
474 | + return ipa_data.get('memberof_group', ()), stage, \ | |
475 | + ipa_data.get('randompassword') | |
476 | + | |
477 | + | |
478 | +#########################[ Get FreeIPA group members ]######################### | |
479 | +def get_group(api, group, gid, description, idview, group_cache={}): | |
480 | + try: | |
481 | + return group_cache[group] | |
482 | + except KeyError: | |
483 | + ipa_group = ipa_update_create(api, 'group', 'group', group, | |
484 | + add_params={'description': description}) | |
485 | + result = group_cache[group] = ipa_group.get('member_user', []) | |
486 | + | |
487 | + if idview: # Update or create idoverride for group? | |
488 | + ipa_update_create(api, 'idoverridegroup', 'GID override', idview, | |
489 | + group, gidnumber=gid, cn=group, add_params={ | |
490 | + 'description': "Added by %s while syncronizing %s with %s" \ | |
491 | + % (PROG_NAME, group, args.ldapserver) }) | |
492 | + return result | |
493 | + | |
494 | + | |
495 | +######################[ Update FreeIPA group membership ]###################### | |
496 | +def group_commit(command, desc, group, updates): | |
497 | + logger.info('Updating FreeIPA group %s, %s: %s', group, desc, updates) | |
498 | + getattr(api.Command, command)(group, user=list(updates)) | |
499 | + | |
500 | +def group_queue(command, desc, groups, users, commit, maxqueue=0, queue={}): | |
501 | + if groups and users: | |
502 | + for group in (groups,) if isinstance(groups, str) else groups: | |
503 | + try: | |
504 | + queued = queue[group] | |
505 | + queued.update((users,) if isinstance(users, str) else users) | |
506 | + if not commit and len(queued) > maxqueue: | |
507 | + group_commit(command, desc, group, queued) | |
508 | + del queue[group] | |
509 | + except KeyError: | |
510 | + queue[group] = set((users,) if isinstance(users,str) else users) | |
511 | + if commit and queue: | |
512 | + for group, updates in queue.items(): | |
513 | + group_commit(command, desc, group, updates) | |
514 | + queue.clear() | |
515 | + | |
516 | +def group_add(api, groups=None, users=None, commit=False, maxq=100, queue={}): | |
517 | + group_queue('group_add_member', 'adding', groups, users, commit, maxq,queue) | |
518 | + | |
519 | +def group_del(api, groups=None, users=None, commit=False, maxq=100, queue={}): | |
520 | + group_queue('group_remove_member','removing',groups,users,commit,maxq,queue) | |
521 | + | |
522 | + | |
523 | +############################################################################### | |
524 | +def attr_replace(data, attr, value, param=None): | |
525 | + """Remove/overwrite data[option] based on value, return inital data[option]. | |
526 | + parameters: | |
527 | + data - dict to update | |
528 | + option - attribute in data to update | |
529 | + value - if ''-->delete, if None-->no change, else overwrite with value | |
530 | + param - if value contains %s, it will be replaced by this value | |
531 | + """ | |
532 | + result = data.get(attr) | |
533 | + if value: | |
534 | + data[attr] = value % userid if '%s' in value else value | |
535 | + elif value == '' and result is not None: | |
536 | + del data[attr] | |
537 | + return result | |
538 | +def attr_remove(data, attr): return attr_replace(data, attr, '', None) | |
539 | + | |
540 | + | |
541 | +if __name__ == '__main__': | |
542 | + logging.basicConfig(format=LOG_FORMAT) | |
543 | + args = parse_args() | |
544 | + | |
545 | + try: | |
546 | + logger.debug('connecting to FreeIPA') | |
547 | + if api.isdone('finalize') is False: | |
548 | + api.bootstrap_with_global_options(context='api') | |
549 | + api.finalize() | |
550 | + api.Backend.rpcclient.connect() | |
551 | + | |
552 | + logger.info('Connecting to LDAP server %s', args.ldapserver) | |
553 | + ldap = args.ldapconnection(args.ldapserver, args.basedn) | |
554 | + | |
555 | + if not ldap.check_schema(exists=not args.cleanup_schema, | |
556 | + update_schema=args.update_schema or args.cleanup_schema): | |
557 | + logger.error("Required LDAP schema customizations not in FreeIPA") | |
558 | + exit(1) | |
559 | + elif args.cleanup_schema: | |
560 | + print("LDAP schema customizations are removed from FreeIPA") | |
561 | + exit(0) | |
562 | + | |
563 | + if args.idview: # Ensure IDView exists (if specified) | |
564 | + ipa_update_create(api, 'idview', 'Compatibility View', args.idview, | |
565 | + add_params={ 'description': 'Created by %s while syncronizing ' | |
566 | + 'with %s' % (PROG_NAME, args.ldapserver) }) | |
567 | + | |
568 | + logger.info('searching for users') | |
569 | + excl_users = ldap.get_group_members(*args.x_group) | set(args.x_user) | |
570 | + users = ldap.get_group_members(*args.user_group) | set(args.user) | |
571 | + for dn, user_data in ldap.get_users(*users, excl_users=excl_users, | |
572 | + customfilter=args.filter): | |
573 | + user, *aliases = attr_remove(user_data, 'uid') | |
574 | + if aliases: | |
575 | + logger.warn('ignoring additional userid\'s for user %s: %s', | |
576 | + user,', '.join(aliases)) | |
577 | + if not args.migrate_password: | |
578 | + attr_remove(user_data, 'userpassword') | |
579 | + uid=attr_remove(user_data, 'uidnumber') | |
580 | + gid=attr_remove(user_data, 'gidnumber') | |
581 | + homedir=attr_replace(user_data,'homedirectory',args.homedir,user) | |
582 | + loginshell=attr_replace(user_data,'loginshell',args.loginshell,user) | |
583 | + | |
584 | + in_groups, is_stage, password = process_user(api, user, user_data, | |
585 | + stage=args.stage, enforce_password=bool(args.password_logfile)) | |
586 | + | |
587 | + if password: | |
588 | + with open(args.password_logfile, 'a') as file: | |
589 | + print(user, password, user_data.get('givenname',''), | |
590 | + user_data.get('sn',''), user_data.get('cn',''), | |
591 | + ','.join(user_data.get('mail','')), sep='\t', file=file) | |
592 | + | |
593 | + if is_stage: | |
594 | + logger.debug('not processing group membership or ID overrides ' | |
595 | + 'for stage user %s', user) | |
596 | + continue | |
597 | + | |
598 | + if args.idview: # Update or create the idoverride for the user? | |
599 | + ipa_update_create(api, 'idoverrideuser', 'UID/GID override', | |
600 | + args.idview, user, uidnumber=uid, gidnumber=gid, | |
601 | + homedirectory=homedir, loginshell=loginshell, | |
602 | + add_params={ 'description': | |
603 | + "Added by %s while syncronizing %s with %s" | |
604 | + % (PROG_NAME, user, args.ldapserver)}) | |
605 | + | |
606 | + if args.group is not None: | |
607 | + remaining_groups = list(in_groups) if not args.group else \ | |
608 | + [ g for g in in_groups if g in args.group ] | |
609 | + for group, gid, desc in ldap.get_user_groups(user, args.group): | |
610 | + if user not in get_group(api,group,gid,desc,args.idview): | |
611 | + logger.debug('adding user %s to group %s', user, group) | |
612 | + group_add(api, group, user) | |
613 | + if group in remaining_groups: | |
614 | + remaining_groups.remove(group) | |
615 | + if remaining_groups: | |
616 | + logger.debug('removing user %s from group(s) %s', user, | |
617 | + ', '.join(remaining_groups)) | |
618 | + group_del(api, remaining_groups, user) | |
619 | + | |
620 | + group_add(api, commit=True) | |
621 | + group_del(api, commit=True) | |
622 | + except LDAPError as e: | |
623 | + logger.critical("Error with LDAP commmunication: %s", e) | |
624 | + except AuthenticationError: | |
625 | + logger.critical("Unable to authenticate to FreeIPA, " | |
626 | + "make sure you have a valid Kerberos ticket!") | |
627 | + except PublicError as e: | |
628 | + logger.critical("error while communicating with FreeIPA: %s", e) | |
629 | + else: | |
630 | + exit(0) | |
631 | + exit(1) | |
632 | + | |
... | ... |