├── .github
├── FUNDING.yml
├── screenshot.png
└── workflows
│ └── build_packages.yml
├── .gitignore
├── LICENSE.txt
├── README.md
├── assets
├── LAPS4LINUX.desktop
├── laps-runner.cron
├── laps.icns
├── laps.ico
├── laps.png
├── setup.icns
├── setup.ico
└── setup.png
├── docs
└── OpenLDAP.md
├── installer
├── deb
│ ├── build.sh
│ ├── laps4linux-client
│ │ └── DEBIAN
│ │ │ ├── control
│ │ │ └── postinst
│ └── laps4linux-runner
│ │ └── DEBIAN
│ │ ├── conffiles
│ │ ├── control
│ │ └── postinst
├── macos
│ └── build.sh
├── rpm
│ ├── build.sh
│ └── rpmbuild
│ │ └── SPECS
│ │ ├── laps4linux-client.spec
│ │ └── laps4linux-runner.spec
└── windows
│ ├── installer-top-img.bmp
│ └── setup.iss
├── laps-client
├── README.md
├── laps-cli-script.py
├── laps-client-settings.json.example
├── laps-client.linux.spec
├── laps-client.macos.spec
├── laps-client.windows.spec
├── laps-gui-script.py
├── laps_client
│ ├── __init__.py
│ ├── filetime.py
│ ├── laps_cli.py
│ └── laps_gui.py
├── requirements-barcode.txt
├── requirements.txt
└── setup.py
└── laps-runner
├── README.md
├── laps-runner-pam
├── laps-runner-script.py
├── laps-runner.json.example
├── laps-runner.linux.spec
├── laps_runner
├── __init__.py
├── filetime.py
└── laps_runner.py
├── requirements.txt
└── setup.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: ['schorschii']
2 | liberapay: schorschii
3 | custom: ['https://www.paypal.me/schorschii']
4 |
--------------------------------------------------------------------------------
/.github/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/.github/screenshot.png
--------------------------------------------------------------------------------
/.github/workflows/build_packages.yml:
--------------------------------------------------------------------------------
1 | name: Release with packages
2 |
3 | on:
4 | workflow_dispatch: # allow manual execution
5 | push:
6 | tags:
7 | - 'v*'
8 |
9 | jobs:
10 | create_release_deb: # used to identify the output in other jobs
11 | name: Create Release with Debian and RPM package
12 | runs-on: self-hosted
13 |
14 | permissions:
15 | contents: write
16 |
17 | outputs:
18 | upload_url: ${{ steps.create_release.outputs.upload_url }}
19 | version: ${{ steps.get_version.outputs.version }}
20 |
21 | steps:
22 | - name: Checkout code
23 | uses: actions/checkout@v3
24 |
25 | - name: Install dependencies
26 | run: |
27 | sudo apt update && sudo apt install -y rpm rpmlint qttools5-dev-tools qtchooser libkrb5-dev python3-venv python3-pip $(cat installer/deb/laps4linux-client/DEBIAN/control | grep 'Depends' | cut -d: -f2 | sed -e 's/,/ /g' | sed -r 's/\([<>=.0-9]+\)//g') $(cat installer/deb/laps4linux-runner/DEBIAN/control | grep 'Depends' | cut -d: -f2 | sed -e 's/,/ /g' | sed -r 's/\([<>=.0-9]+\)//g')
28 |
29 | - id: get_version
30 | name: Get version name for Github release title
31 | run: cd laps-client && echo "version=$(python3 -c 'import laps_client; print(laps_client.__version__)')" >> $GITHUB_OUTPUT
32 |
33 | - name: Compile LAPS-Client
34 | run: |
35 | cd laps-client
36 | python3 -m venv venv
37 | venv/bin/pip3 install --upgrade pip
38 | venv/bin/pip3 install pyinstaller .[barcode]
39 | venv/bin/pyinstaller laps-client.linux.spec
40 |
41 | - name: Compile LAPS-Runner
42 | run: |
43 | cd laps-runner
44 | python3 -m venv venv
45 | venv/bin/pip3 install --upgrade pip
46 | venv/bin/pip3 install pyinstaller .
47 | venv/bin/pyinstaller laps-runner.linux.spec
48 |
49 | - name: Execute deb build
50 | run: cd installer/deb/ && ./build.sh
51 |
52 | - name: Execute rpm build
53 | run: cd installer/rpm/ && ./build.sh
54 |
55 | - id: create_release
56 | name: Create Github release
57 | uses: actions/create-release@v1
58 | env:
59 | # this token is provided automatically by Actions with permissions declared above
60 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
61 | with:
62 | draft: true # create a release draft - only the master of disaster is allowed to publish it
63 | prerelease: false
64 | release_name: Version ${{ steps.get_version.outputs.version }}
65 | tag_name: ${{ github.ref }}
66 |
67 | - name: Upload deb client artifact
68 | uses: actions/upload-release-asset@v1
69 | env:
70 | GITHUB_TOKEN: ${{ github.token }}
71 | with:
72 | upload_url: ${{ steps.create_release.outputs.upload_url }}
73 | asset_path: installer/deb/laps4linux-client.deb
74 | asset_name: laps4linux-client-${{ steps.get_version.outputs.version }}.deb
75 | asset_content_type: application/vnd.debian.binary-package
76 | - name: Upload deb runner artifact
77 | uses: actions/upload-release-asset@v1
78 | env:
79 | GITHUB_TOKEN: ${{ github.token }}
80 | with:
81 | upload_url: ${{ steps.create_release.outputs.upload_url }}
82 | asset_path: installer/deb/laps4linux-runner.deb
83 | asset_name: laps4linux-runner-${{ steps.get_version.outputs.version }}.deb
84 | asset_content_type: application/vnd.debian.binary-package
85 |
86 | - name: Get rpm client artifact
87 | run: |
88 | echo "ARTIFACT_PATH=$(find installer/rpm -name "laps4linux-client-*.rpm")" >> $GITHUB_ENV
89 | echo "ARTIFACT_NAME=$(basename $(find installer/rpm -name "laps4linux-client-*.rpm"))" >> $GITHUB_ENV
90 | - name: Upload rpm client artifact
91 | uses: actions/upload-release-asset@v1
92 | env:
93 | GITHUB_TOKEN: ${{ github.token }}
94 | with:
95 | upload_url: ${{ steps.create_release.outputs.upload_url }}
96 | asset_path: ${{ env.ARTIFACT_PATH }}
97 | asset_name: ${{ env.ARTIFACT_NAME }}
98 | asset_content_type: application/vnd.debian.binary-package
99 | - name: Get rpm runner artifact
100 | run: |
101 | echo "ARTIFACT_PATH=$(find installer/rpm -name "laps4linux-runner-*.rpm")" >> $GITHUB_ENV
102 | echo "ARTIFACT_NAME=$(basename $(find installer/rpm -name "laps4linux-runner-*.rpm"))" >> $GITHUB_ENV
103 | - name: Upload rpm runner artifact
104 | uses: actions/upload-release-asset@v1
105 | env:
106 | GITHUB_TOKEN: ${{ github.token }}
107 | with:
108 | upload_url: ${{ steps.create_release.outputs.upload_url }}
109 | asset_path: ${{ env.ARTIFACT_PATH }}
110 | asset_name: ${{ env.ARTIFACT_NAME }}
111 | asset_content_type: application/vnd.debian.binary-package
112 |
113 | create_pkg:
114 | name: Create macOS package
115 | runs-on: macos-13
116 | needs: create_release_deb
117 |
118 | permissions:
119 | contents: write
120 |
121 | steps:
122 | - name: Checkout code
123 | uses: actions/checkout@v3
124 |
125 | - name: Install Python
126 | uses: actions/setup-python@v5
127 | with:
128 | python-version: '3.8'
129 |
130 | - name: Importing signing certificates
131 | run: |
132 | # create and unlock temporary keychain
133 | KEYCHAIN_NAME=$RUNNER_TEMP/build.keychain
134 | KEYCHAIN_PASS=$(head -c 8 /dev/urandom | od -An -tu8 | awk '{$1=$1};1')
135 | security create-keychain -p $KEYCHAIN_PASS $KEYCHAIN_NAME
136 | security default-keychain -s $KEYCHAIN_NAME
137 | security set-keychain-settings -lut 21600 $KEYCHAIN_NAME
138 | security unlock-keychain -p $KEYCHAIN_PASS $KEYCHAIN_NAME
139 |
140 | # add certificate to keychain
141 | CERT_FILE=build.p12
142 | echo "${{ secrets.DEVELOPER_ID_APPLICATION_CERT_BASE64 }}" | base64 --decode > $CERT_FILE
143 | security import $CERT_FILE -k $KEYCHAIN_NAME -P "${{ secrets.DEVELOPER_ID_APPLICATION_CERT_PASSWORD }}" -T /usr/bin/codesign >/dev/null 2>&1
144 | rm -fr $CERT_FILE
145 | #security find-identity -v #-p codesigning
146 |
147 | # enable codesigning from a non user interactive shell
148 | security set-key-partition-list -S apple-tool:,apple: -s -k $KEYCHAIN_PASS $KEYCHAIN_NAME >/dev/null 2>&1
149 |
150 | - name: Create venv, install Python packages, compile binaries
151 | run: |
152 | cd laps-client
153 | python -m venv venv
154 | venv/bin/pip3 install pyinstaller .[barcode]
155 | venv/bin/pyinstaller laps-client.macos.spec
156 | cd ..
157 |
158 | - name: Execute package build
159 | run: cd installer/macos/ && ./build.sh
160 | env:
161 | DEVELOPER_ACCOUNT_USERNAME: ${{ secrets.DEVELOPER_ACCOUNT_USERNAME }}
162 | DEVELOPER_ACCOUNT_PASSWORD: ${{ secrets.DEVELOPER_ACCOUNT_PASSWORD }}
163 | DEVELOPER_ACCOUNT_TEAM: ${{ secrets.DEVELOPER_ACCOUNT_TEAM }}
164 |
165 | - name: Purging signing keychain
166 | run: |
167 | security delete-keychain $RUNNER_TEMP/build.keychain
168 |
169 | - name: Upload artifact
170 | uses: actions/upload-release-asset@v1
171 | env:
172 | GITHUB_TOKEN: ${{ github.token }}
173 | with:
174 | upload_url: ${{ needs.create_release_deb.outputs.upload_url }}
175 | asset_path: installer/macos/laps4linux-client.dmg
176 | asset_name: laps4linux-client-${{ needs.create_release_deb.outputs.version }}.dmg
177 | asset_content_type: application/octet-stream
178 |
179 | create_exe:
180 | name: Create Windows package
181 | runs-on: windows-2022
182 | needs: create_release_deb
183 |
184 | permissions:
185 | contents: write
186 |
187 | steps:
188 | - name: Checkout code
189 | uses: actions/checkout@v3
190 |
191 | - name: Install Python
192 | uses: actions/setup-python@v5
193 | with:
194 | python-version: '3.8'
195 |
196 | - name: Create venv, install Python packages, compile binaries
197 | run: |
198 | cd laps-client
199 | python -m venv venv
200 | venv/Scripts/pip.exe install pyinstaller==5.13.2 .[barcode]
201 | venv/Scripts/pyinstaller.exe laps-client.windows.spec
202 | cd ..
203 |
204 | - name: Execute package build
205 | shell: cmd
206 | run: cd installer\windows\ && "%programfiles(x86)%\Inno Setup 6\iscc.exe" "setup.iss"
207 |
208 | - name: Upload artifact
209 | uses: actions/upload-release-asset@v1
210 | env:
211 | GITHUB_TOKEN: ${{ github.token }}
212 | with:
213 | upload_url: ${{ needs.create_release_deb.outputs.upload_url }}
214 | asset_path: installer/windows/laps4linux-client.exe
215 | asset_name: laps4linux-client-${{ needs.create_release_deb.outputs.version }}.exe
216 | asset_content_type: application/vnd.microsoft.portable-executable
217 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 |
3 | test*.py
4 |
5 | __pycache__/
6 |
7 | build/
8 | dist/
9 |
10 | *.egg-info/
11 | venv/
12 |
13 | installer/windows/*.exe
14 | installer/macos/target/*
15 | installer/deb/*.deb
16 | installer/deb/laps4linux-*/*
17 | !installer/deb/laps4linux-*/DEBIAN/
18 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 |
635 | Copyright (C)
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 .
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 | Copyright (C)
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 | .
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 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # LAPS4LINUX
4 | Linux and macOS implementation of the Local Administrator Password Solution (LAPS) from Microsoft.
5 |
6 | LAPS is a system which periodically changes local admin passwords on domain computers and stores them (encrypted) in the LDAP directory (i.e. Active Directory), where domain administrators can decrypt and view them. This ensures that people who leave the company do not have access to local admin accounts anymore and that every local admin has a strong unique password set.
7 |
8 | ## Client
9 | The management client enables administrators to view the current (decrypted) local admin passwords. It can be used from command line or as graphical application.
10 |
11 | The client is also executable under Windows and provides an improved UI compared with the original tools from Microsoft and additional features (e.g. display additional LDAP values, directly start remote connections and it can be called with `laps://` protocol scheme parameter to directly start search).
12 |
13 | Read [README.md in the laps-client dir](laps-client/) for more information.
14 |
15 | ## Runner
16 | The runner is responsible for periodically rotating the admin password of a Linux client and updating it in the LDAP directory.
17 |
18 | Read [README.md in the laps-runner dir](laps-runner/) for more information.
19 |
20 | ## Support for both Legacy and Native LAPS
21 | Microsoft introducted the new "Native LAPS" in 2023. In contrast to Legacy LAPS, the new version uses different LDAP attributes and has the option to store the password encrypted in the LDAP directory. LAPS4LINUX supports both versions out-of-the-box. The client will search for a password in the following order: Native LAPS encrypted, Native LAPS unencrypted, Legacy LAPS (unencrypted).
22 |
23 | The runner can operate in Legacy or Native mode by switching the setting `native-laps` to `true` or `false`. In Native mode, the runner stores the password and username as JSON string in the LDAP attribute, as defined by Microsoft. In addition to that, when in Native mode, you can set `security-descriptor` to a valid SID in your domain and the runner will encrypt the password for this user/group. Please note: only SID security descriptors are supported (e.g. `S-1-5-21-2185496602-3367037166-1388177638-1103`), do not use group names (`DOMAIN\groupname`). If you enable encryption, you should also change `ldap-attribute-password` to `msLAPS-EncryptedPassword` to store the encrypted password in the designated LDAP attribute for compatibility with other Tools. Please have a look at the runner section below for more information.
24 |
25 | For de-/encryption, the Python [dpapi-ng library](https://github.com/jborean93/dpapi-ng) is used.
26 |
27 | ## More Information
28 | - [LAPS4LINUX 💘 OpenLDAP](docs/OpenLDAP.md)
29 |
--------------------------------------------------------------------------------
/assets/LAPS4LINUX.desktop:
--------------------------------------------------------------------------------
1 | [Desktop Entry]
2 | Type=Application
3 | Name=LAPS4LINUX
4 | Exec=/usr/bin/laps-gui %u
5 | Terminal=false
6 | MimeType=x-scheme-handler/laps;
7 | Icon=/usr/share/pixmaps/laps.png
8 | Categories=Application;Utility
9 | Comment=Linux implementation of the Local Administrator Password Solution (LAPS) GUI from Microsoft.
10 |
11 | # execute `update-desktop-database` after copying into /usr/share/applications
12 |
--------------------------------------------------------------------------------
/assets/laps-runner.cron:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # example file for `/etc/cron.hourly/laps-runner`
4 |
5 | SHELL=/bin/sh
6 | PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
7 |
8 | OUT=$(/usr/sbin/laps-runner --config /etc/laps-runner.json 2>&1)
9 |
10 | if [ -f /usr/bin/logger ]; then
11 | echo $OUT | /usr/bin/logger -t laps-runner
12 | fi
13 |
--------------------------------------------------------------------------------
/assets/laps.icns:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/assets/laps.icns
--------------------------------------------------------------------------------
/assets/laps.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/assets/laps.ico
--------------------------------------------------------------------------------
/assets/laps.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/assets/laps.png
--------------------------------------------------------------------------------
/assets/setup.icns:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/assets/setup.icns
--------------------------------------------------------------------------------
/assets/setup.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/assets/setup.ico
--------------------------------------------------------------------------------
/assets/setup.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/assets/setup.png
--------------------------------------------------------------------------------
/docs/OpenLDAP.md:
--------------------------------------------------------------------------------
1 | # LAPS4LINUX 💘 OpenLDAP
2 | This document describes how LAPS(4LINUX) can be used with OpenLDAP. This guide assumes that you already have an OpenLDAP server set up and running. A short overview / cookbook for a basic OpenLDAP setup can be found in my [OpenLDAP Cheat Sheet](https://gist.github.com/schorschii/0dcd19d4abb74bd3d52de12bff91657b).
3 |
4 | All LAPS4LINUX features can be used with OpenLDAP **except password encryption**, since the encryption relies on proprietary RPC calls only available on Windows Server.
5 |
6 | ## 1. Kerberos Setup
7 | The LAPS runner uses Kerberos for authentication, therefore you need to set up Kerberos authentication for your OpenLDAP. [This guide](https://ubuntu.com/server/docs/how-to-set-up-kerberos-with-openldap-backend) from Ubuntu describes how to configure a Kerberos server (can be run on the same server as known from Microsoft AD) by using your OpenLDAP as backend.
8 |
9 | After your Kerberos server is running, you need to create a principal and a corresponding keytab for your OpenLDAP server to enable Kerberos authentication in your OpenLDAP.
10 | ```
11 | $ kadmin.local
12 | addprinc -randkey ldap/openldap.example.com
13 | ktadd -k /etc/krb5.keytab ldap/openldap.example.com@EXAMPLE.COM
14 | ```
15 |
16 | ## 2. Extend the Schema
17 | You need to add attributes to your schema where to store the administrator passwords. We are using the same names and OIDs like the [original attributes from Microsoft](https://learn.microsoft.com/en-us/windows-server/identity/laps/laps-technical-reference), but the syntax OIDs are replaced with the corresponding OpenLDAP counterparts.
18 |
19 | Add this dynamic config via `ldapmodify -Y EXTERNAL -H ldapi:///`:
20 | ```
21 | dn: cn=laps,cn=schema,cn=config
22 | changetype: add
23 | objectClass: olcSchemaConfig
24 | cn: laps
25 | olcAttributeTypes: {0}( 1.2.840.113556.1.6.44.1.1 NAME 'msLAPS-PasswordExpirationTime' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )
26 | olcAttributeTypes: {1}( 1.2.840.113556.1.6.44.1.2 NAME 'msLAPS-Password' SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
27 | olcAttributeTypes: {2}( 1.2.840.113556.1.6.44.1.3 NAME 'msLAPS-EncryptedPassword' SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 )
28 | olcAttributeTypes: {3}( 1.2.840.113556.1.6.44.1.4 NAME 'msLAPS-EncryptedPasswordHistory' SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 )
29 | olcAttributeTypes: {4}( 1.2.840.113556.1.6.44.1.5 NAME 'msLAPS-EncryptedDSRMPassword' SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 )
30 | olcAttributeTypes: {5}( 1.2.840.113556.1.6.44.1.6 NAME 'msLAPS-EncryptedDSRMPasswordHistory' SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 )
31 | olcAttributeTypes: {5}( 1.2.840.113556.1.6.44.1.7 NAME 'msLAPS-CurrentPasswordVersion' SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 )
32 |
33 | olcObjectClasses: {0}( 1.1.3.7.1 NAME 'computer' DESC 'Computer object' SUP person STRUCTURAL MAY ( msLAPS-PasswordExpirationTime $ msLAPS-Password $ msLAPS-EncryptedPassword $ msLAPS-EncryptedPasswordHistory $ msLAPS-EncryptedDSRMPassword $ msLAPS-EncryptedDSRMPasswordHistory $ msLAPS-CurrentPasswordVersion ) )
34 | ```
35 |
36 | ## 3. Create Appropriate ACLs
37 | You need to add ACLs so that only a group of administrators can read and the computer itself can write the LAPS attributes.
38 |
39 | OpenLDAP ACLs are tricky and highly depend on your existing ACLs since the order is important. Therefore, the following example may needs to be adjusted for your specific OpenLDAP setup!
40 |
41 | `ldapmodify -Y EXTERNAL -H ldapi:///`:
42 | ```
43 | dn: olcDatabase={1}mdb,cn=config
44 | changetype: modify
45 | add: olcAccess
46 | olcAccess: {0} to attrs=msLAPS-PasswordExpirationTime,msLAPS-Password,msLAPS-EncryptedPassword,msLAPS-EncryptedPasswordHistory,msLAPS-EncryptedDSRMPassword,msLAPS-EncryptedDSRMPasswordHistory,msLAPS-CurrentPasswordVersion
47 | by self write
48 | by group/groupOfNames/member=cn=LAPS-ADMINS,dc=example,dc=com read
49 | by * none
50 | ```
51 |
52 | Since the setup is still not complex enough, when authenticating via Kerberos (GSSAPI), the username seen by OpenLDAP is in form of `uid=computername,[cn=example.com,]cn=gssapi,cn=auth` instead of the object's DN `cn=computername,ou=computer,dc=example,dc=com`. You can imagine that the previously configured ACL "[...] by self write" permission does not take effect because of this. For that, we need to configure an identity mapping as described in the [OpenLDAP docs](https://www.openldap.org/doc/admin26/sasl.html).
53 |
54 | `ldapmodify -Y EXTERNAL -H ldapi:///`:
55 | ```
56 | dn: cn=config
57 | changetype: modify
58 | add: olcAuthzRegexp
59 | olcAuthzRegexp: {0}uid=(.+),cn=gssapi,cn=auth ldap:///dc=example,dc=com??one?(krbPrincipalName:caseIgnoreIA5Match:=$1\40EXAMPLE.COM)
60 | ```
61 |
62 | Note that `\40` in the LDAP URI represents an escaped `@` char.
63 |
64 | ## 4. Join your Client Computer to the OpenLDAP
65 | Create an object for your LAPS-managed computer in your LDAP directory, e.g. `cn=vm-VirtualBox,dc=example,dc=com`. Use our custom class `computer` for these objects. Then, create a Kerberos principal and keytab for this computer object:
66 | ```
67 | $ kadmin.local
68 | addprinc -randkey -x dn=cn=vm-VirtualBox,dc=example,dc=com VM-VIRTUALBOX$@EXAMPLE.COM
69 | ktadd -k /tmp/krb5.keytab VM-VIRTUALBOX$@EXAMPLE.COM
70 | ```
71 |
72 | This example uses an uppercase principal name with trailing dollar sign to follow the ugly Microsoft way. Of course you are free to use lowercase chars without dollar sign, but then you need to manually edit the "hostname" field in `/etc/laps-runner.json` on the LAPS managed computer.
73 |
74 | Move the generated `/tmp/krb5.keytab` to `/etc/krb5.keytab` on the target LAPS managed computer. Restrict the access to the root user.
75 |
76 | ## 5. Execute the Runner
77 | Adjust your LAPS Runner config as described in the Runner [README.md](../laps-runner/README.md) (set LDAP attributes, decide if Native LAPS should be used etc.).
78 |
79 | And finally you can execute the runner on the managed computer and it will generate an admin password and store it in your OpenLDAP. Yay!
80 |
--------------------------------------------------------------------------------
/installer/deb/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | # cd to working dir
5 | cd "$(dirname "$0")"
6 |
7 |
8 | # build client .deb package
9 | INSTALLDIR=/usr/share/laps4linux-client
10 | BUILDDIR=laps4linux-client
11 |
12 | # empty / create necessary directories
13 | if [ -d "$BUILDDIR/usr" ]; then
14 | rm -r $BUILDDIR/usr
15 | fi
16 | mkdir -p $BUILDDIR/usr/share
17 |
18 | # copy files in place
19 | cp -r ../../laps-client/dist/laps-client $BUILDDIR/$INSTALLDIR
20 | install -D -m 644 ../../assets/laps.png -t $BUILDDIR/usr/share/pixmaps
21 | install -D -m 644 ../../assets/LAPS4LINUX.desktop -t $BUILDDIR/usr/share/applications
22 |
23 | # make binaries available in PATH
24 | mkdir -p $BUILDDIR/usr/bin
25 | ln -sf $INSTALLDIR/laps-gui $BUILDDIR/usr/bin/laps-gui
26 | ln -sf $INSTALLDIR/laps-cli $BUILDDIR/usr/bin/laps-cli
27 |
28 |
29 | # build runner .deb package
30 | INSTALLDIR=/usr/share/laps4linux-runner
31 | BUILDDIR=laps4linux-runner
32 |
33 | # empty / create necessary directories
34 | if [ -d "$BUILDDIR/usr" ]; then
35 | rm -r $BUILDDIR/usr
36 | fi
37 | mkdir -p $BUILDDIR/usr/share
38 |
39 | # copy files in place
40 | cp -r ../../laps-runner/dist/laps-runner $BUILDDIR/$INSTALLDIR
41 | install -D -m 755 ../../assets/laps-runner.cron $BUILDDIR/etc/cron.hourly/laps-runner
42 | install -D -m 755 ../../laps-runner/laps-runner-pam -t $BUILDDIR/usr/sbin
43 |
44 | # test if we have our own laps-runner config
45 | if [ -f ../../laps-runner/laps-runner.json ]; then
46 | install -D -m 644 ../../laps-runner/laps-runner.json $BUILDDIR/etc/laps-runner.json
47 | else
48 | echo 'WARNING: You are using the example json config file, make sure this is intended'
49 | install -D -m 644 ../../laps-runner/laps-runner.json.example $BUILDDIR/etc/laps-runner.json
50 | fi
51 |
52 | # make binaries available in PATH
53 | mkdir -p $BUILDDIR/usr/sbin
54 | ln -sf $INSTALLDIR/laps-runner $BUILDDIR/usr/sbin/laps-runner
55 |
56 |
57 | # build debs
58 | dpkg-deb -Zxz --root-owner-group --build laps4linux-client
59 | dpkg-deb -Zxz --root-owner-group --build laps4linux-runner
60 |
61 | echo "Build finished"
62 |
--------------------------------------------------------------------------------
/installer/deb/laps4linux-client/DEBIAN/control:
--------------------------------------------------------------------------------
1 | Package: laps4linux-client
2 | Version: 1.13.1
3 | Section: base
4 | Priority: optional
5 | Architecture: all
6 | Depends: desktop-file-utils, libxcb-xinerama0, libxcb-cursor0
7 | Conflicts: laps4linux, laps4linux-gui, laps4linux-cli
8 | Maintainer: Georg Sieber
9 | Description: Linux implementation of the Local Administrator Password Solution (LAPS) GUI from Microsoft.
10 | This package contains the management client GUI und CLI for viewing the admin passwords and setting new expiration dates.
11 |
12 |
--------------------------------------------------------------------------------
/installer/deb/laps4linux-client/DEBIAN/postinst:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # exit on error
4 | set -e
5 |
6 | # source debconf library.
7 | #. /usr/share/debconf/confmodule
8 |
9 | # register protocol scheme handler
10 | update-desktop-database
11 |
--------------------------------------------------------------------------------
/installer/deb/laps4linux-runner/DEBIAN/conffiles:
--------------------------------------------------------------------------------
1 | /etc/laps-runner.json
2 |
--------------------------------------------------------------------------------
/installer/deb/laps4linux-runner/DEBIAN/control:
--------------------------------------------------------------------------------
1 | Package: laps4linux-runner
2 | Version: 1.13.1
3 | Section: base
4 | Priority: optional
5 | Architecture: all
6 | Depends: krb5-user
7 | Conflicts: laps4linux, laps4linux-gui, laps4linux-cli
8 | Maintainer: Georg Sieber
9 | Description: Linux implementation of the Local Administrator Password Solution (LAPS) from Microsoft.
10 | This package contains the LAPS runner for automatically changing the local admin password. In order to use the runner, the machine needs to be joined into your domain using Samba 'net ads join', PBIS 'domainjoin-cli join' or 'adcli join'. Please adjust the config file /etc/laps-runner.ini and check if LDAP access is working by executing 'laps-runner -f'.
11 |
12 |
--------------------------------------------------------------------------------
/installer/deb/laps4linux-runner/DEBIAN/postinst:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # exit on error
4 | set -e
5 |
6 | # source debconf library.
7 | #. /usr/share/debconf/confmodule
8 |
9 |
--------------------------------------------------------------------------------
/installer/macos/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | cd "$(dirname "$0")"
4 |
5 | SRC_DIR="../../laps-client/dist"
6 | DMG_FILE_TMP_MOUNT="/Volumes/LAPS4LINUX"
7 | DMG_FILE_TMP="laps4linux-rw.dmg"
8 | DMG_FILE="laps4linux-client.dmg"
9 | #DEVELOPER_ACCOUNT_USERNAME=""
10 | #DEVELOPER_ACCOUNT_PASSWORD=""
11 | #DEVELOPER_ACCOUNT_TEAM=""
12 |
13 |
14 | # remove temp build folder
15 | rm -r "$SRC_DIR/LAPS4LINUX"
16 |
17 |
18 | # check if mount point is free
19 | if [ -d "$DMG_FILE_TMP_MOUNT" ]; then
20 | echo "ERROR: $DMG_FILE_TMP_MOUNT already mounted"
21 | exit 1
22 | fi
23 |
24 |
25 | # create DMG with .app directory and /Applications link
26 | rm "$SRC_DIR/.DS_Store"
27 | hdiutil create -srcfolder "$SRC_DIR" -volname "LAPS4LINUX" -fs HFS+ -fsargs "-c c=64,a=16,e=16" -format UDRW "$DMG_FILE_TMP"
28 | hdiutil attach -readwrite -noverify -noautoopen "$DMG_FILE_TMP"
29 | ln -s "/Applications" "$DMG_FILE_TMP_MOUNT/Applications"
30 |
31 |
32 | # set volume icon
33 | cp "../../assets/setup.icns" "$DMG_FILE_TMP_MOUNT/.VolumeIcon.icns"
34 | SetFile -c icnC "$DMG_FILE_TMP_MOUNT/.VolumeIcon.icns"
35 | SetFile -a C "$DMG_FILE_TMP_MOUNT"
36 |
37 |
38 | # create final DMG
39 | sleep 1
40 | rm -rf "$DMG_FILE_TMP_MOUNT/.fseventsd"
41 | hdiutil detach "$DMG_FILE_TMP_MOUNT"
42 | sleep 1
43 | hdiutil convert "$DMG_FILE_TMP" -format UDZO -o "$DMG_FILE"
44 | rm "$DMG_FILE_TMP"
45 |
46 |
47 | # notarize (only possible with valid signature)
48 | if [ "$DEVELOPER_ACCOUNT_USERNAME" != "" ] && [ "$DEVELOPER_ACCOUNT_PASSWORD" != "" ] && [ "$DEVELOPER_ACCOUNT_TEAM" != "" ]; then
49 | echo "Store credentials for notarization ..."
50 | xcrun notarytool store-credentials "notarytool-password" --apple-id "$DEVELOPER_ACCOUNT_USERNAME" --password "$DEVELOPER_ACCOUNT_PASSWORD" --team-id "$DEVELOPER_ACCOUNT_TEAM"
51 | fi
52 |
53 | echo "Notarize package ..."
54 | xcrun notarytool submit "$DMG_FILE" --wait --keychain-profile "notarytool-password"
55 |
56 | # get logfile with additional information:
57 | # xcrun notarytool log --keychain-profile "notarytool-password" xxx-xxx-xxx-xxx developer_log.json
58 |
59 |
60 | echo "Build finished"
61 |
--------------------------------------------------------------------------------
/installer/rpm/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | # build .rpm packages
5 |
6 | # cd to working dir
7 | cd "$(dirname "$0")"
8 |
9 | # ensure that the rpm build tools are installed
10 | if command -v yum; then
11 | yum install -y rpmdevtools rpmlint
12 | fi
13 | if command -v rpmdev-setuptree; then
14 | rpmdev-setuptree
15 | fi
16 |
17 | # get the version from the python script
18 | VERSION=$(cd ../../laps-client && python3 -c 'import laps_client; print(laps_client.__version__)')
19 |
20 | # generate and fill the source folders
21 | mkdir -p laps4linux-client-$VERSION/usr/bin
22 | mkdir -p laps4linux-client-$VERSION/usr/share/
23 | mkdir -p laps4linux-client-$VERSION/usr/share/applications
24 | mkdir -p laps4linux-client-$VERSION/usr/share/pixmaps
25 | cp -r ../../laps-client/dist/laps-client laps4linux-client-$VERSION/usr/share/laps4linux-client
26 | cp ../../assets/LAPS4LINUX.desktop laps4linux-client-$VERSION/usr/share/applications
27 | cp ../../assets/laps.png laps4linux-client-$VERSION/usr/share/pixmaps
28 | ln -sf /usr/share/laps4linux-client/laps-cli laps4linux-client-$VERSION/usr/bin/laps-cli
29 | ln -sf /usr/share/laps4linux-client/laps-gui laps4linux-client-$VERSION/usr/bin/laps-gui
30 |
31 | mkdir -p laps4linux-runner-$VERSION/usr/sbin
32 | mkdir -p laps4linux-runner-$VERSION/usr/share/
33 | mkdir -p laps4linux-runner-$VERSION/etc/cron.hourly
34 | cp -r ../../laps-runner/dist/laps-runner laps4linux-runner-$VERSION/usr/share/laps4linux-runner
35 | cp ../../assets/laps-runner.cron laps4linux-runner-$VERSION/etc/cron.hourly/laps-runner
36 | cp ../../laps-runner/laps-runner-pam laps4linux-runner-$VERSION/usr/sbin/laps-runner-pam
37 | ln -sf /usr/share/laps4linux-runner/laps-runner laps4linux-runner-$VERSION/usr/sbin/laps-runner
38 | chmod +x laps4linux-runner-$VERSION/etc/cron.hourly/laps-runner
39 |
40 | # test if we have our own laps-runner config
41 | if [ -f ../../laps-runner/laps-runner.json ]; then
42 | cp ../../laps-runner/laps-runner.json laps4linux-runner-$VERSION/etc
43 | else
44 | echo 'WARNING: You are using the example json config file, make sure this is intended'
45 | cp ../../laps-runner/laps-runner.json.example laps4linux-runner-$VERSION/etc/laps-runner.json
46 | fi
47 |
48 | # create .tar.gz source package
49 | tar --create --file laps4linux-client-$VERSION.tar.gz laps4linux-client-$VERSION
50 | tar --create --file laps4linux-runner-$VERSION.tar.gz laps4linux-runner-$VERSION
51 | if [ ! -f laps4linux-runner-$VERSION.tar.gz ] || [ ! -f laps4linux-client-$VERSION.tar.gz ]; then
52 | echo 'Tar file was not detected, exiting'
53 | exit 1
54 | fi
55 |
56 | # remove out build directory, now that we have our tarball
57 | rm -fr laps4linux-client-$VERSION
58 | rm -fr laps4linux-runner-$VERSION
59 | mkdir -p rpmbuild/SOURCES
60 | mv laps4linux-client-$VERSION.tar.gz rpmbuild/SOURCES/
61 | mv laps4linux-runner-$VERSION.tar.gz rpmbuild/SOURCES/
62 |
63 | # build the rpm package
64 | cd rpmbuild
65 | rpmbuild --define "_topdir $(pwd)" -bb SPECS/laps4linux-client.spec
66 | rpmbuild --define "_topdir $(pwd)" -bb SPECS/laps4linux-runner.spec
67 |
68 | # uninstall: rpm -e laps4linux-client
69 | # install: rpm -i ...rpm
70 | # list: rpm -qlp ...rpm
71 |
--------------------------------------------------------------------------------
/installer/rpm/rpmbuild/SPECS/laps4linux-client.spec:
--------------------------------------------------------------------------------
1 | Name: laps4linux-client
2 | Version: 1.13.1
3 | Release: 1%{?dist}
4 | Summary: Laps4linux - auto-rotate the root password for AD bound (samba net, pbis, adcli) linux servers
5 | #BuildArch: noarch
6 |
7 | License: GPL-3.0
8 | URL: https://github.com/schorschii/LAPS4LINUX
9 | Source0: %{name}-%{version}.tar.gz
10 |
11 | Requires: krb5-devel gcc
12 | AutoReqProv: no
13 |
14 | %description
15 | This RPM contains the script and personalized config to run the lap4linux python script
16 |
17 | %define _build_id_links none
18 |
19 | %prep
20 | %setup -q
21 |
22 |
23 | %build
24 |
25 |
26 | %install
27 | rm -rf $RPM_BUILD_ROOT
28 |
29 | mkdir -p $RPM_BUILD_ROOT/usr/share
30 | cp -R usr/share/laps4linux-client $RPM_BUILD_ROOT/usr/share
31 | mkdir -p $RPM_BUILD_ROOT/%{_bindir}
32 | cp -P usr/bin/laps-gui $RPM_BUILD_ROOT/%{_bindir}/laps-gui
33 | cp -P usr/bin/laps-cli $RPM_BUILD_ROOT/%{_bindir}/laps-cli
34 | mkdir -p $RPM_BUILD_ROOT/usr/share/applications
35 | cp usr/share/applications/LAPS4LINUX.desktop $RPM_BUILD_ROOT/usr/share/applications
36 | mkdir -p $RPM_BUILD_ROOT/usr/share/pixmaps
37 | cp usr/share/pixmaps/laps.png $RPM_BUILD_ROOT/usr/share/pixmaps
38 |
39 |
40 | %post
41 | if command -v update-desktop-database; then
42 | update-desktop-database
43 | fi
44 |
45 |
46 | %clean
47 | rm -rf $RPM_BUILD_ROOT
48 |
49 |
50 | %files
51 | %{_bindir}/laps-gui
52 | %{_bindir}/laps-cli
53 | /usr/share/laps4linux-client
54 | /usr/share/applications/LAPS4LINUX.desktop
55 | /usr/share/pixmaps/laps.png
56 |
57 |
58 | %changelog
59 | * Wed Jan 04 2023 schorschii
60 | - Initial build
61 |
--------------------------------------------------------------------------------
/installer/rpm/rpmbuild/SPECS/laps4linux-runner.spec:
--------------------------------------------------------------------------------
1 | Name: laps4linux-runner
2 | Version: 1.13.1
3 | Release: 1%{?dist}
4 | Summary: Laps4linux - auto-rotate the root password for AD bound (samba net, pbis, adcli) linux servers
5 | #BuildArch: noarch
6 |
7 | License: GPL-3.0
8 | URL: https://github.com/schorschii/LAPS4LINUX
9 | Source0: %{name}-%{version}.tar.gz
10 |
11 | Requires: krb5-workstation krb5-devel gcc
12 | AutoReqProv: no
13 |
14 | %description
15 | This RPM contains the script and personalized config to run the lap4linux python script
16 |
17 | %define _build_id_links none
18 |
19 | %prep
20 | %setup -q
21 |
22 |
23 | %build
24 |
25 |
26 | %install
27 | rm -rf $RPM_BUILD_ROOT
28 |
29 | mkdir -p $RPM_BUILD_ROOT/usr/share
30 | cp -R usr/share/laps4linux-runner $RPM_BUILD_ROOT/usr/share
31 | mkdir -p $RPM_BUILD_ROOT/%{_sbindir}
32 | cp -P usr/sbin/laps-runner $RPM_BUILD_ROOT/%{_sbindir}/laps-runner
33 | mkdir -p $RPM_BUILD_ROOT/%{_sysconfdir}
34 | cp etc/laps-runner.json $RPM_BUILD_ROOT/%{_sysconfdir}
35 | mkdir -p $RPM_BUILD_ROOT/%{_sysconfdir}/cron.hourly/
36 | cp etc/cron.hourly/laps-runner $RPM_BUILD_ROOT/%{_sysconfdir}/cron.hourly/
37 | mkdir -p $RPM_BUILD_ROOT/%{_sbindir}
38 | cp usr/sbin/laps-runner-pam $RPM_BUILD_ROOT/%{_sbindir}/laps-runner-pam
39 |
40 | %post
41 |
42 |
43 | %clean
44 | rm -rf $RPM_BUILD_ROOT
45 |
46 |
47 | %files
48 | %{_sbindir}/laps-runner
49 | %{_sbindir}/laps-runner-pam
50 | %{_sysconfdir}/laps-runner.json
51 | %{_sysconfdir}/cron.hourly/laps-runner
52 | /usr/share/laps4linux-runner
53 |
54 |
55 | %changelog
56 | * Wed Jan 04 2023 schorschii
57 | - Renamed packages to laps4linux-client and laps4linux-runner
58 | - Adjusted dependencies for CentOS 9
59 |
60 | * Thu Jan 13 2022 novaksam
61 | - Initial build
62 |
--------------------------------------------------------------------------------
/installer/windows/installer-top-img.bmp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/schorschii/LAPS4LINUX/a75fb908942b856b4ab9d562cc0f70b3a239e722/installer/windows/installer-top-img.bmp
--------------------------------------------------------------------------------
/installer/windows/setup.iss:
--------------------------------------------------------------------------------
1 | ; Script generated by the Inno Setup Script Wizard.
2 | ; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
3 |
4 | #define MyAppName "LAPS4LINUX"
5 | #define MyAppVersion "1.13.1"
6 | #define MyAppPublisher "Sieber Systems"
7 | #define MyAppURL "https://github.com/schorschii/LAPS4LINUX"
8 | #define MyAppExeName "laps-gui.exe"
9 | #define MyAppDir "C:\Program Files\"+MyAppName
10 |
11 | [Setup]
12 | ; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications.
13 | ; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
14 | AppId={{D6992D04-3289-4F43-93EA-F84B0F5FC008}
15 | AppName={#MyAppName}
16 | AppVersion={#MyAppVersion}
17 | ;AppVerName={#MyAppName} {#MyAppVersion}
18 | AppPublisher={#MyAppPublisher}
19 | AppPublisherURL={#MyAppURL}
20 | AppSupportURL={#MyAppURL}
21 | AppUpdatesURL={#MyAppURL}
22 | WizardSmallImageFile="installer-top-img.bmp"
23 | UninstallDisplayName={#MyAppName}
24 | UninstallDisplayIcon="{#MyAppDir}\\{#MyAppExeName},0"
25 | DefaultDirName={#MyAppDir}
26 | DisableDirPage=yes
27 | DisableProgramGroupPage=yes
28 | ; Uncomment the following line to run in non administrative install mode (install for current user only.)
29 | ;PrivilegesRequired=lowest
30 | OutputDir=.
31 | OutputBaseFilename=laps4linux-client
32 | Compression=lzma
33 | SolidCompression=yes
34 | WizardStyle=modern
35 | SetupIconFile=..\..\assets\setup.ico
36 |
37 | [Languages]
38 | Name: "english"; MessagesFile: "compiler:Default.isl"
39 |
40 | [Tasks]
41 | Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
42 |
43 | [Registry]
44 | Root: HKCR; Subkey: "laps"; Flags: uninsdeletekey
45 | Root: HKCR; Subkey: "laps"; ValueType: string; ValueName: ""; ValueData: "URL:Local Administrator Password Solution"
46 | Root: HKCR; Subkey: "laps"; ValueType: string; ValueName: "URL Protocol"; ValueData: ""
47 | Root: HKCR; Subkey: "laps\shell"; Flags: uninsdeletekey
48 | Root: HKCR; Subkey: "laps\shell\open"; Flags: uninsdeletekey
49 | Root: HKCR; Subkey: "laps\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """C:\Program Files\LAPS4LINUX\laps-gui.exe"" %1"
50 |
51 | [Files]
52 | Source: "..\..\laps-client\dist\LAPS4LINUX\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
53 | Source: "..\..\laps-client\dist\LAPS4LINUX\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
54 | ; NOTE: Don't use "Flags: ignoreversion" on any shared system files
55 |
56 | [Icons]
57 | Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
58 | Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
59 |
60 | [Run]
61 | Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
62 |
--------------------------------------------------------------------------------
/laps-client/README.md:
--------------------------------------------------------------------------------
1 | # LAPS4LINUX Client
2 | The management client enables administrators to easily view the current (decrypted) local admin passwords and the Bitlocker recovery key too. It can be used from command line or as graphical application.
3 |
4 | ### Graphical User Interface (GUI)
5 | 
6 |
7 | With a right click on the attribute text boxes, you can display the content as barcode or QR code. With this, you can scan the password using an USB QR/barcode scanner to easily enter it on the client machine without typing it on the keyboard.
8 |
9 | ### Command Line Interface (CLI)
10 | ```
11 | $ laps-cli notebook01 --set-expiry "2021-04-28 01:01:01"
12 | LAPS4LINUX CLI v1.0.0
13 | https://github.com/schorschii/laps4linux
14 |
15 | 🔑 Password for »ldapuser«:
16 | Connection: ldapserver01: user@example.com
17 | Found: CN=NOTEBOOK01,OU=NOTEBOOKS,DC=example,DC=com
18 | Password: abc123
19 | Expiration: 132641316610000000 (2021-04-29 01:01:01)
20 | New Expiration: 132640452610000000 (2021-04-28 01:01:01)
21 | Expiration Date Changed Successfully.
22 |
23 |
24 | $ laps-cli "*"
25 | LAPS4LINUX CLI v1.0.0
26 | https://github.com/schorschii/laps4linux
27 |
28 | 🔑 Password for »ldapuser«:
29 | Connection: ldapserver01: user@example.com
30 | NOTEBOOK01$ : abc123
31 | NOTEBOOK02$ : 123abc
32 | ...
33 | ```
34 |
35 | ### Installation
36 | It is recommended to use the installation package provided on the [Github releases](https://github.com/schorschii/LAPS4LINUX/releases) page.
37 |
38 | Manual installation in a Python venv:
39 | ```
40 | # install available python modules globally to avoid duplicate install in venv
41 | apt install python3-venv python3-pip python3-setuptools python3-qtpy python3-gssapi python3-dnspython python3-pycryptodome libkrb5-dev
42 |
43 | python3 -m venv venv --system-site-packages
44 | venv/bin/pip3 install .
45 |
46 | venv/bin/laps-gui
47 | venv/bin/laps-cli
48 | ```
49 |
50 | ### Configuration
51 | By default, the clients will try to auto-discover your domain and LDAP servers via DNS. If this does not succeed, the client will ask you for this values and write it to the config file `~/.config/laps-client/settings.json`.
52 |
53 | You can create a preset config file `/etc/laps-client.json` which will be loaded if `~/.config/laps-client/settings.json` does not exist. With this, you can distribute default settings (all relevant LDAP attributes, SSL on etc.) for new users.
54 |
55 |
56 | Configuration Values
57 |
58 | - `server`: Array of domain controllers with items like `{"address": "dc1.example.com", "port": 389, "ssl": false}`. Leave empty for DNS auto discovery.
59 | - `domain`: Your domain name (e.g. `example.com`). Leave empty for DNS auto discovery.
60 | - `ldap-query`: LDAP filter for getting the computer object, default: `(&(objectClass=computer)(cn=%1))`. `%1` is replaced by the computer name.
61 | - `use-starttls`: Boolean which indicates wheter to use StartTLS on unencrypted LDAP connections (requires valid server certificate).
62 | - `username`: The username for LDAP simple binds. For Microsoft AD, you need to append the domain (`user@example.com`). For OpenLDAP, you need to enter your user DN (`dn=user,dc=example,dc=com`).
63 | - `use-kerberos`: Boolean which indicates wheter to use Kerberos for LDAP bind before falling back to simple bind.
64 | - `ldap-attributes`: A dict of LDAP attributes to display.
65 | - Dict key is the display name and the corresponding value is the LDAP attribute name.
66 | - The dict value can also be a list of strings. Then, the first non-empty LDAP attribute will be displayed. This is useful when migrating to Native LAPS - you can display the new attribute value if exists, otherwise the old attribute value of Legacy LAPS is shown.
67 | - When appending `sub:` to the dict value (= LDAP attribute name), the sub-enrties of the computer object are searched. This is useful for querying the Bitlocker recovery key (`sub:msFVE-RecoveryPassword`). Make sure that you have permission to view the Bitlocker keys!
68 | - `ldap-attribute-password`: The LDAP attribute name which contains the admin password. The client will try to decrypt this value (in case of Native LAPS) and use it for Remmina connections. Can also be a list of strings.
69 | - `ldap-attribute-password-expiry`: The LDAP attribute name which contains the admin password expiration date. The client will write the updated expiration date into this attribute. Can also be a list of strings.
70 | - `ldap-attribute-password-history`: The LDAP attribute name which contains the admin password history. The client will try to decrypt this value (in case of Native LAPS) and use it to display the password history. Can also be a list of strings.
71 | - `connect-username`: The username which will be used for Remmina connections. May be modified by the client during the runtime since Native LAPS also stores username information.
72 |
73 |
74 | If you want to view the DSRM password, simply put `msLAPS-EncryptedDSRMPassword` and `msLAPS-EncryptedDSRMPasswordHistory` into the `ldap-attributes` and `ldap-attribute-password`|`ldap-attribute-password-history` configuration.
75 |
76 | ### Kerberos Authentication
77 | The client (both GUI and CLI) supports Kerberos authentication which means you can use the client without entering a password if you are logged in with a domain account and have a valid Kerberos ticket (for this, an SSL connection is required). If not, ldap3's "simple" authentication is used as fallback and the client will ask you for username and password. The Kerberos authentication attempt can be disabled by setting `use-kerberos` to `false` in the config file.
78 |
79 | If you did not automatically received a Kerberos ticket on login, you can manually aquire a ticket via `kinit @`.
80 |
81 | ### SSL Connection
82 | By default, LAPS4LINUX (client and runner) will connect via LDAP on port 389 to your Active Directory and upgrade the connection via STARTTLS to an encrypted one. This means that your server needs a valid certificate and STARTTLS enabled. This behavior can be disabled by modifying the `use-starttls` in the config file, but it is strongly discouraged to disable it since sensitive data is transferred.
83 |
84 | Alternatively, you can use LDAPS by editing the config file (`~/.config/laps-client/settings.json`): modify the server entry and set `ssl` to `true` and `port` to `636` (see example below). You can also configure multiple static LDAP servers in the config file.
85 |
86 | ### Domain Forest Searches
87 | If you are managing multiple domains, you probably want to search for a computer in all domains. Please use the global catalog for this by setting the option `gc-port` in the configuration file of all servers, e.g. to `3268` (LDAP) or `3269` (LDAPS).
88 |
89 |
90 | Example
91 |
92 | ```
93 | {
94 | "server": [
95 | {
96 | "address": "dc.example.com",
97 | "port": 636,
98 | "gc-port": 3269,
99 | "ssl": true
100 | },
101 | .....
102 | ],
103 | .....
104 | }
105 | ```
106 |
107 |
108 | Since the global catalog is read only, LAPS4LINUX will switch to "normal" LDAP(S) port when you want to change the password expiry date. That's why, the `port` option is still required even if a `gc-port` is given!
109 |
110 | ### Query Additional Attributes (Customization)
111 | LAPS4LINUX allows you to query additional attributes besides the admin password which might be of interest for you. For that, just edit the config file `~/.config/laps-client/settings.json` and enter the additional LDAP attributes you'd like to query into the settings array `"ldap-attributes"`.
112 |
113 | The setting `ldap-attribute-password-expiry` defines in which LDAP attribute the date will be written when selecting a new expiration date. If you like, you can hide the "Set Expiration" button by entering an empty string for this setting.
114 |
115 | With the setting `ldap-attribute-password` you define which LDAP attribute is considered as the admin password (for usage with the Remmina connect feature).
116 |
117 | ### Remote Access
118 | On Linux, the GUI allows you to directly open RDP or SSH connections via Remmina from the menu. Please make sure you have installed the latest Remmina with RDP and SSH extensions. You can change the username which is used for the connection in the client config (`"connect-username": "administrator"`).
119 |
120 |
121 | Flatpak Remmina
122 |
123 | If you use Remmina installed via Flatpak, you need to create the following wrapper script which calls the Flatpak version of remmina. Do not forget to make it executable.
124 |
125 | ```
126 | *** /usr/local/bin/remmina ***
127 |
128 | #!/bin/bash
129 | flatpak run org.remmina.Remmina $@
130 | ```
131 |
132 |
133 | ### Windows and macOS
134 | The clients (GUI and CLI) are also executable under Windows and macOS. It's ported to Windows because of the additional features that the original LAPS GUI did not have (query custom attributes, OCO integration).
135 |
136 | ### `laps://` Protocol Scheme
137 | The GUI supports the protocol scheme `laps://`, which means you can call the GUI like `laps-gui.py laps://HOSTNAME` to automatically search `HOSTNAME` after startup. This feature is mainly intended to use with the [OCO server](https://github.com/schorschii/OCO-Server) web frontend ("[COMPUTER_COMMANDS](https://github.com/schorschii/OCO-Server/blob/master/docs/Computers.md#client-commands)").
138 |
139 |
140 | Linux
141 |
142 | On Linux, you need to create file `/usr/share/applications/LAPS4LINUX-protocol-handler.desktop` with the following content and execute `update-desktop-database`.
143 | ```
144 | [Desktop Entry]
145 | Type=Application
146 | Name=LAPS4LINUX Protocol Handler
147 | Exec=/usr/bin/laps-gui %u
148 | StartupNotify=false
149 | MimeType=x-scheme-handler/laps;
150 | NoDisplay=true
151 | ```
152 |
153 |
154 |
155 | macOS
156 |
157 | On macOS, the protocol handler is registered using the Info.plist file (setting "CFBundleURLTypes") in the .app directory.
158 | Please use laps-gui.macos.spec with pyinstaller to automatically create an .app directory which registers itself for the laps:// protocol on first launch.
159 |
160 |
161 |
162 | Windows
163 |
164 | On Windows, you need to set the following registry values:
165 | ```
166 | Windows Registry Editor Version 5.00
167 |
168 | [HKEY_CLASSES_ROOT\laps]
169 | @="URL:LAPS"
170 | "URL Protocol"=""
171 |
172 | [HKEY_CLASSES_ROOT\laps\shell]
173 |
174 | [HKEY_CLASSES_ROOT\laps\shell\open]
175 |
176 | [HKEY_CLASSES_ROOT\laps\shell\open\command]
177 | @="\"C:\\Program Files\\LAPS4WINDOWS\\laps-gui.exe\" %1"
178 | ```
179 |
180 |
--------------------------------------------------------------------------------
/laps-client/laps-cli-script.py:
--------------------------------------------------------------------------------
1 | import laps_client.laps_cli
2 | laps_client.laps_cli.main()
3 |
--------------------------------------------------------------------------------
/laps-client/laps-client-settings.json.example:
--------------------------------------------------------------------------------
1 | {
2 | "server": [
3 | {
4 | "address": "dc1.example.com",
5 | "port": 636,
6 | "ssl": true
7 | },
8 | {
9 | "address": "dc2.example.com",
10 | "port": 636,
11 | "ssl": true
12 | },
13 | {
14 | "address": "dc3.example.com",
15 | "port": 636,
16 | "ssl": true
17 | }
18 | ],
19 | "use-starttls": true,
20 | "domain": "example.com",
21 | "ldap-query": "(&(objectClass=computer)(cn=%1))",
22 |
23 | "username": "johndoe",
24 | "use-kerberos": true,
25 |
26 | "ldap-attribute-password": [
27 | "msLAPS-EncryptedPassword",
28 | "msLAPS-Password",
29 | "ms-Mcs-AdmPwd"
30 | ],
31 | "ldap-attribute-password-expiry": [
32 | "msLAPS-PasswordExpirationTime",
33 | "ms-Mcs-AdmPwdExpirationTime"
34 | ],
35 | "ldap-attribute-password-history": "msLAPS-EncryptedPasswordHistory",
36 | "ldap-attributes": {
37 | "Operating System": "operatingSystem",
38 | "Last Logon Timestamp": "lastLogonTimestamp",
39 | "Bitlocker Recovery Key": "sub:msFVE-RecoveryPassword",
40 | "Administrator Password": [
41 | "msLAPS-EncryptedPassword",
42 | "msLAPS-Password",
43 | "ms-Mcs-AdmPwd"
44 | ],
45 | "Password Expiration Date": [
46 | "msLAPS-PasswordExpirationTime",
47 | "ms-Mcs-AdmPwdExpirationTime"
48 | ],
49 | "Administrator Password History": "msLAPS-EncryptedPasswordHistory"
50 | },
51 |
52 | "connect-username": "administrator"
53 | }
54 |
--------------------------------------------------------------------------------
/laps-client/laps-client.linux.spec:
--------------------------------------------------------------------------------
1 | # -*- mode: python ; coding: utf-8 -*-
2 | from PyInstaller.utils.hooks import collect_submodules
3 |
4 | hiddenimports = []
5 | hiddenimports += collect_submodules('gssapi.raw')
6 |
7 | block_cipher = None
8 |
9 | gui_a = Analysis(
10 | ['laps-gui-script.py'],
11 | pathex=['.'],
12 | binaries=[],
13 | datas=[ ('../assets/laps.png', '.') ],
14 | hiddenimports=hiddenimports,
15 | hookspath=[],
16 | runtime_hooks=[],
17 | excludes=[],
18 | cipher=block_cipher,
19 | noarchive=False,
20 | optimize=0,
21 | )
22 | cli_a = Analysis(
23 | ['laps-cli-script.py'],
24 | pathex=['.'],
25 | binaries=[],
26 | datas=[ ('../assets/laps.png', '.') ],
27 | hiddenimports=hiddenimports,
28 | hookspath=[],
29 | runtime_hooks=[],
30 | excludes=[],
31 | cipher=block_cipher,
32 | noarchive=False,
33 | optimize=0,
34 | )
35 | MERGE( (gui_a, 'laps-gui', 'laps-gui'), (cli_a, 'laps-cli', 'laps-cli') )
36 |
37 | gui_pyz = PYZ(gui_a.pure, gui_a.zipped_data, cipher=block_cipher)
38 | gui_exe = EXE(gui_pyz, gui_a.scripts, [],
39 | exclude_binaries=True,
40 | name='laps-gui',
41 | contents_directory='.',
42 | debug=False,
43 | bootloader_ignore_signals=False,
44 | strip=False,
45 | upx=True,
46 | console=False,
47 | disable_windowed_traceback=False,
48 | argv_emulation=False,
49 | target_arch=None,
50 | codesign_identity=None,
51 | entitlements_file=None,
52 | )
53 |
54 | cli_pyz = PYZ(cli_a.pure, cli_a.zipped_data, cipher=block_cipher)
55 | cli_exe = EXE(cli_pyz, cli_a.scripts, [],
56 | exclude_binaries=True,
57 | name='laps-cli',
58 | contents_directory='.',
59 | debug=False,
60 | bootloader_ignore_signals=False,
61 | strip=False,
62 | upx=True,
63 | console=True,
64 | disable_windowed_traceback=False,
65 | argv_emulation=False,
66 | target_arch=None,
67 | codesign_identity=None,
68 | entitlements_file=None,
69 | )
70 |
71 | coll = COLLECT(
72 | gui_exe, gui_a.binaries, gui_a.zipfiles, gui_a.datas,
73 | cli_exe, cli_a.binaries, cli_a.zipfiles, cli_a.datas,
74 | strip=False,
75 | upx=True,
76 | upx_exclude=[],
77 | name='laps-client'
78 | )
79 |
--------------------------------------------------------------------------------
/laps-client/laps-client.macos.spec:
--------------------------------------------------------------------------------
1 | # -*- mode: python ; coding: utf-8 -*-
2 |
3 | block_cipher = None
4 | version = '1.13.1'
5 |
6 | # find the SHA-1 hash of you Developer ID Application certificate
7 | # for signing via `security find-identity -v -p codesigning` or use `None`
8 | codesign_identity = '4B7092469383AAFE294DA4B2B0CCB1BB0050DF72'
9 |
10 | def Entrypoint(dist, group, name, **kwargs):
11 | import pkg_resources
12 |
13 | # get toplevel packages of distribution from metadata
14 | def get_toplevel(dist):
15 | distribution = pkg_resources.get_distribution(dist)
16 | if distribution.has_metadata('top_level.txt'):
17 | return list(distribution.get_metadata('top_level.txt').split())
18 | else:
19 | return []
20 |
21 | kwargs.setdefault('hiddenimports', [])
22 | packages = []
23 | for distribution in kwargs['hiddenimports']:
24 | packages += get_toplevel(distribution)
25 |
26 | kwargs.setdefault('pathex', [])
27 | # get the entry point
28 | ep = pkg_resources.get_entry_info(dist, group, name)
29 | # insert path of the egg at the verify front of the search path
30 | kwargs['pathex'] = [ep.dist.location] + kwargs['pathex']
31 | # script name must not be a valid module name to avoid name clashes on import
32 | script_path = os.path.join(workpath, name + '-script.py')
33 | print("creating script for entry point", dist, group, name)
34 | with open(script_path, 'w') as fh:
35 | print("import", ep.module_name, file=fh)
36 | print("%s.%s()" % (ep.module_name, '.'.join(ep.attrs)), file=fh)
37 | for package in packages:
38 | print("import", package, file=fh)
39 |
40 | return Analysis(
41 | [script_path] + kwargs.get('scripts', []),
42 | **kwargs
43 | )
44 |
45 | gui_a = Entrypoint('laps4linux_client', 'gui_scripts', 'laps-gui',
46 | pathex=[],
47 | binaries=[],
48 | datas=[],
49 | hiddenimports=[],
50 | hookspath=[],
51 | hooksconfig={},
52 | runtime_hooks=[],
53 | excludes=[],
54 | win_no_prefer_redirects=False,
55 | win_private_assemblies=False,
56 | cipher=block_cipher,
57 | noarchive=False
58 | )
59 | cli_a = Entrypoint('laps4linux_client', 'console_scripts', 'laps-cli',
60 | pathex=[],
61 | binaries=[],
62 | datas=[],
63 | hiddenimports=[],
64 | hookspath=[],
65 | hooksconfig={},
66 | runtime_hooks=[],
67 | excludes=[],
68 | win_no_prefer_redirects=False,
69 | win_private_assemblies=False,
70 | cipher=block_cipher,
71 | noarchive=False
72 | )
73 | MERGE( (gui_a, 'laps-gui', 'laps-gui'), (cli_a, 'laps-cli', 'laps-cli') )
74 |
75 | gui_pyz = PYZ(gui_a.pure, gui_a.zipped_data, cipher=block_cipher)
76 | gui_exe = EXE(gui_pyz, gui_a.scripts, [],
77 | exclude_binaries=True,
78 | name='laps-gui',
79 | debug=False,
80 | bootloader_ignore_signals=False,
81 | strip=False,
82 | upx=True,
83 | console=False,
84 | disable_windowed_traceback=False,
85 | target_arch=None,
86 | codesign_identity=codesign_identity,
87 | entitlements_file=None,
88 | argv_emulation=True
89 | )
90 |
91 | cli_pyz = PYZ(cli_a.pure, cli_a.zipped_data, cipher=block_cipher)
92 | cli_exe = EXE(cli_pyz, cli_a.scripts, [],
93 | exclude_binaries=True,
94 | name='laps-cli',
95 | debug=False,
96 | bootloader_ignore_signals=False,
97 | strip=False,
98 | upx=True,
99 | console=False,
100 | disable_windowed_traceback=False,
101 | target_arch=None,
102 | codesign_identity=codesign_identity,
103 | entitlements_file=None
104 | )
105 |
106 | coll = COLLECT(
107 | gui_exe, gui_a.binaries, gui_a.zipfiles, gui_a.datas,
108 | cli_exe, cli_a.binaries, cli_a.zipfiles, cli_a.datas,
109 | strip=False,
110 | upx=True,
111 | upx_exclude=[],
112 | name='LAPS4LINUX'
113 | )
114 |
115 | app = BUNDLE(coll,
116 | name='LAPS4LINUX.app',
117 | icon='../assets/laps.icns',
118 | bundle_identifier='systems.sieber.laps4mac',
119 | version=version,
120 | info_plist={
121 | 'CFBundleURLTypes': [
122 | {
123 | 'CFBundleURLName': 'Local Administrator Password Solution',
124 | 'CFBundleTypeRole': 'Viewer',
125 | 'CFBundleURLSchemes': ['laps']
126 | }
127 | ]
128 | }
129 | )
130 |
--------------------------------------------------------------------------------
/laps-client/laps-client.windows.spec:
--------------------------------------------------------------------------------
1 | # -*- mode: python ; coding: utf-8 -*-
2 |
3 | block_cipher = None
4 |
5 | def Entrypoint(dist, group, name, **kwargs):
6 | import pkg_resources
7 |
8 | # get toplevel packages of distribution from metadata
9 | def get_toplevel(dist):
10 | distribution = pkg_resources.get_distribution(dist)
11 | if distribution.has_metadata('top_level.txt'):
12 | return list(distribution.get_metadata('top_level.txt').split())
13 | else:
14 | return []
15 |
16 | kwargs.setdefault('hiddenimports', [])
17 | packages = []
18 | for distribution in kwargs['hiddenimports']:
19 | packages += get_toplevel(distribution)
20 |
21 | kwargs.setdefault('pathex', [])
22 | # get the entry point
23 | ep = pkg_resources.get_entry_info(dist, group, name)
24 | # insert path of the egg at the verify front of the search path
25 | kwargs['pathex'] = [ep.dist.location] + kwargs['pathex']
26 | # script name must not be a valid module name to avoid name clashes on import
27 | script_path = os.path.join(workpath, name + '-script.py')
28 | print("creating script for entry point", dist, group, name)
29 | with open(script_path, 'w') as fh:
30 | print("import", ep.module_name, file=fh)
31 | print("%s.%s()" % (ep.module_name, '.'.join(ep.attrs)), file=fh)
32 | for package in packages:
33 | print("import", package, file=fh)
34 |
35 | return Analysis(
36 | [script_path] + kwargs.get('scripts', []),
37 | **kwargs
38 | )
39 |
40 | gui_a = Entrypoint('laps4linux_client', 'gui_scripts', 'laps-gui',
41 | pathex=['.'],
42 | binaries=[],
43 | datas=[ ('..\\assets\\laps.png', '.') ],
44 | hiddenimports=['winkerberos', 'cryptography'],
45 | hookspath=[],
46 | runtime_hooks=[],
47 | excludes=[],
48 | win_no_prefer_redirects=False,
49 | win_private_assemblies=False,
50 | cipher=block_cipher,
51 | noarchive=False
52 | )
53 | cli_a = Entrypoint('laps4linux_client', 'console_scripts', 'laps-cli',
54 | pathex=['.'],
55 | binaries=[],
56 | datas=[ ('..\\assets\\laps.png', '.') ],
57 | hiddenimports=['winkerberos', 'cryptography'],
58 | hookspath=[],
59 | runtime_hooks=[],
60 | excludes=[],
61 | win_no_prefer_redirects=False,
62 | win_private_assemblies=False,
63 | cipher=block_cipher,
64 | noarchive=False
65 | )
66 | MERGE( (gui_a, 'laps-gui', 'laps-gui'), (cli_a, 'laps-cli', 'laps-cli') )
67 |
68 | gui_pyz = PYZ(gui_a.pure, gui_a.zipped_data, cipher=block_cipher)
69 | gui_exe = EXE(gui_pyz, gui_a.scripts, [],
70 | exclude_binaries=True,
71 | name='laps-gui',
72 | icon='..\\assets\\laps.ico',
73 | contents_directory='.',
74 | debug=False,
75 | bootloader_ignore_signals=False,
76 | strip=False,
77 | upx=True,
78 | console=False
79 | )
80 |
81 | cli_pyz = PYZ(cli_a.pure, cli_a.zipped_data, cipher=block_cipher)
82 | cli_exe = EXE(cli_pyz, cli_a.scripts, [],
83 | exclude_binaries=True,
84 | name='laps-cli',
85 | icon='..\\assets\\laps.ico',
86 | contents_directory='.',
87 | debug=False,
88 | bootloader_ignore_signals=False,
89 | strip=False,
90 | upx=True,
91 | console=True
92 | )
93 |
94 | coll = COLLECT(
95 | gui_exe, gui_a.binaries, gui_a.zipfiles, gui_a.datas,
96 | cli_exe, cli_a.binaries, cli_a.zipfiles, cli_a.datas,
97 | strip=False,
98 | upx=True,
99 | upx_exclude=[],
100 | name='LAPS4LINUX'
101 | )
102 |
--------------------------------------------------------------------------------
/laps-client/laps-gui-script.py:
--------------------------------------------------------------------------------
1 | import laps_client.laps_gui
2 | laps_client.laps_gui.main()
3 |
--------------------------------------------------------------------------------
/laps-client/laps_client/__init__.py:
--------------------------------------------------------------------------------
1 | __title__ = 'LAPS4LINUX'
2 | __author__ = 'Georg Sieber'
3 | __copyright__ = '© 2021-2025'
4 | __license__ = 'GPL-3.0'
5 | __version__ = '1.13.1'
6 | __website__ = 'https://github.com/schorschii/LAPS4LINUX'
7 |
8 | __all__ = [__author__, __license__, __version__]
9 |
10 |
11 |
12 | import os, sys
13 | import getpass
14 |
15 |
16 | if 'darwin' in sys.platform.lower():
17 | # set OpenSSL path to macOS defaults
18 | # (Github Runner sets this to /usr/local/etc/openssl@1.1/ which does not exist in plain macOS installations)
19 | os.environ['SSL_CERT_FILE'] = '/private/etc/ssl/cert.pem'
20 | os.environ['SSL_CERT_DIR'] = '/private/etc/ssl/certs'
21 | # system CA certs debugging
22 | #import ssl; print(ssl.get_default_verify_paths())
23 | #ctx = ssl.SSLContext(); ctx.load_default_certs(); print(ctx.get_ca_certs())
24 |
25 | def proposeUsername(domain):
26 | return getpass.getuser() + ('@'+domain if domain else '')
27 |
28 | def compileServerUris(servers):
29 | uris = []
30 | for server in servers:
31 | uris.append(
32 | ('ldaps://' if server['ssl'] else 'ldap://')
33 | + str(server['address']) + ':' + str(server['port'])
34 | )
35 | return uris
36 |
--------------------------------------------------------------------------------
/laps-client/laps_client/filetime.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | from datetime import datetime
5 |
6 |
7 | # Microsoft Timestamp Conversion
8 |
9 | EPOCH_TIMESTAMP = 11644473600 # January 1, 1970 as MS file time
10 | HUNDREDS_OF_NANOSECONDS = 10000000
11 |
12 | def dt_to_filetime(dt):
13 | # dt.timestamp() returns UTC time as expected by the LDAP server
14 | return int((dt.timestamp() + EPOCH_TIMESTAMP) * HUNDREDS_OF_NANOSECONDS)
15 |
16 | def filetime_to_dt(ft):
17 | # ft is in UTC, fromtimestamp() converts to local time
18 | return datetime.fromtimestamp(int((ft / HUNDREDS_OF_NANOSECONDS) - EPOCH_TIMESTAMP))
19 |
--------------------------------------------------------------------------------
/laps-client/laps_client/laps_cli.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | from .__init__ import __title__, __version__, __website__, __author__, __copyright__
5 | from .__init__ import proposeUsername
6 | from .filetime import dt_to_filetime, filetime_to_dt
7 |
8 | from pathlib import Path
9 | from os import path, makedirs, rename
10 | from datetime import datetime
11 | from dns import resolver, rdatatype
12 | import dpapi_ng
13 | import ldap3
14 | import ssl
15 | import getpass
16 | import argparse
17 | import json
18 | import sys
19 | import os
20 |
21 |
22 | class LapsCli():
23 | PLATFORM = sys.platform.lower()
24 |
25 | gcModeOn = False
26 | server = None
27 | connection = None
28 | tmpDn = ''
29 |
30 | tlsSettings = ldap3.Tls(validate=ssl.CERT_REQUIRED)
31 |
32 | cfgPresetDirWindows = sys.path[0]
33 | cfgPresetDirUnix = '/etc'
34 | cfgPresetFile = 'laps-client.json'
35 | cfgPresetPath = (cfgPresetDirWindows if sys.platform.lower()=='win32' else cfgPresetDirUnix)+'/'+cfgPresetFile
36 |
37 | cfgDir = str(Path.home())+'/.config/laps-client'
38 | cfgPath = cfgDir+'/settings.json'
39 | cfgVersion = 0
40 | cfgUseKerberos = True
41 | cfgUseStartTls = True
42 | cfgServer = []
43 | cfgDomain = None
44 | cfgLdapQuery = '(&(objectClass=computer)(cn=%1))'
45 | cfgUsername = ''
46 | cfgPassword = ''
47 | cfgLdapAttributes = {
48 | 'Operating System': 'operatingSystem',
49 | 'Administrator Password': ['msLAPS-EncryptedPassword', 'msLAPS-Password', 'ms-Mcs-AdmPwd'],
50 | 'Password Expiration Date': ['msLAPS-PasswordExpirationTime', 'ms-Mcs-AdmPwdExpirationTime'],
51 | 'Administrator Password History': 'msLAPS-EncryptedPasswordHistory'
52 | }
53 | cfgLdapAttributePassword = ['msLAPS-EncryptedPassword', 'msLAPS-Password', 'ms-Mcs-AdmPwd']
54 | cfgLdapAttributePasswordExpiry = ['msLAPS-PasswordExpirationTime', 'ms-Mcs-AdmPwdExpirationTime']
55 | cfgLdapAttributePasswordHistory = 'msLAPS-EncryptedPasswordHistory'
56 |
57 |
58 | def __init__(self, useKerberos=None):
59 | self.LoadSettings()
60 | if(useKerberos != None): self.cfgUseKerberos = useKerberos
61 |
62 | # show version information
63 | print(__title__ + ' CLI Client' +' v'+__version__)
64 | print('If you like LAPS4LINUX please do not forget to give the repository a star ('+__website__+').')
65 |
66 | def GetAttributesAsDict(self):
67 | finalDict = {}
68 | if(isinstance(self.cfgLdapAttributes, list)):
69 | for attribute in self.cfgLdapAttributes:
70 | finalDict[attribute] = attribute
71 | elif(isinstance(self.cfgLdapAttributes, dict)):
72 | for title, attribute in self.cfgLdapAttributes.items():
73 | finalDict[str(title)] = attribute
74 | return finalDict
75 |
76 | def SearchComputer(self, computerName):
77 | # check and escape input
78 | if computerName.strip() == '': return
79 | searchAllComputers = (computerName=='*')
80 | if not searchAllComputers:
81 | computerName = ldap3.utils.conv.escape_filter_chars(computerName)
82 |
83 | # ask for credentials and print connection details
84 | print('')
85 | if not self.checkCredentialsAndConnect(): return
86 | if not searchAllComputers:
87 | self.pushResult('Connection', self.GetConnectionString()) #TODO
88 |
89 | try:
90 | # start LDAP search
91 | count = 0
92 | self.connection.search(
93 | search_base = self.createLdapBase(self.connection),
94 | search_filter = self.cfgLdapQuery.replace('%1', computerName),
95 | attributes = []
96 | )
97 | for entry in self.connection.entries:
98 | count += 1
99 | self.pushResult('Found', entry.entry_dn)
100 | self.tmpDn = entry.entry_dn
101 | self.queryAttributes()
102 | self.printResult(searchAllComputers)
103 |
104 | # no result found
105 | if count == 0:
106 | self.tmpDn = ''
107 | eprint('No result for query »'+computerName+'«')
108 | except Exception as e:
109 | import traceback
110 | print(traceback.format_exc())
111 | # display error
112 | eprint('Error:', str(e))
113 | # reset connection
114 | self.server = None
115 | self.connection = None
116 |
117 | def SetExpiry(self, newExpirationDateTimeString):
118 | # check if dn of target computer object is known
119 | if self.tmpDn.strip() == '': return
120 |
121 | try:
122 | if isinstance(self.cfgLdapAttributePasswordExpiry, list) and len(self.cfgLdapAttributePasswordExpiry) > 0:
123 | attributeExpirationDate = self.cfgLdapAttributePasswordExpiry[0]
124 | else:
125 | attributeExpirationDate = str(self.cfgLdapAttributePasswordExpiry)
126 |
127 | # calc new time
128 | newExpirationDate = datetime.strptime(newExpirationDateTimeString, '%Y-%m-%d %H:%M:%S')
129 | newExpirationDateTime = dt_to_filetime(newExpirationDate)
130 | self.pushResult('New Expiration', str(newExpirationDateTime)+' ('+str(newExpirationDate)+')')
131 |
132 | # start LDAP modify
133 | self.connection.modify(self.tmpDn, { attributeExpirationDate: [(ldap3.MODIFY_REPLACE, [str(newExpirationDateTime)])] })
134 | if self.connection.result['result'] == 0:
135 | print('Expiration Date Changed Successfully.')
136 | else:
137 | print('Unable to change expiration date. '+str(self.connection.result['message']))
138 |
139 | except Exception as e:
140 | # display error
141 | eprint('Error:', str(e))
142 | # reset connection
143 | self.server = None
144 | self.connection = None
145 |
146 | def queryAttributes(self):
147 | if(not self.reconnectForAttributeQuery()):
148 | self.btnSetExpirationTime.setEnabled(False)
149 | self.btnSearchComputer.setEnabled(True)
150 | return
151 |
152 | # start LDAP search
153 | self.connection.search(
154 | search_base = self.tmpDn,
155 | search_filter = '(objectClass=*)',
156 | attributes = ldap3.ALL_ATTRIBUTES
157 | )
158 | # display result
159 | for entry in self.connection.entries:
160 | # we are looking at the main computer object
161 | if(entry.entry_dn == self.tmpDn):
162 | # evaluate attributes of interest
163 | for title, attribute in self.GetAttributesAsDict().items():
164 | if(attribute[:4] == 'sub:'): continue
165 | value = None
166 | if(isinstance(attribute, list)):
167 | for _attribute in attribute:
168 | # use first non-empty attribute
169 | if(str(_attribute) in entry and entry[str(_attribute)]):
170 | value = entry[str(_attribute)]
171 | attribute = str(_attribute)
172 | break
173 | elif(str(attribute) in entry):
174 | value = entry[str(attribute)]
175 |
176 | # handle non-existing attributes
177 | if(value == None):
178 | self.pushResult(str(title), '')
179 |
180 | # if this is the password attribute -> try to parse Native LAPS format
181 | elif(len(value) > 0 and
182 | (str(attribute) == self.cfgLdapAttributePassword or (isinstance(self.cfgLdapAttributePassword, list) and str(attribute) in self.cfgLdapAttributePassword))
183 | ):
184 | password, username, timestamp = self.parseLapsValue(value.values[0])
185 | if(not username or not password):
186 | self.pushResult(str(title), password)
187 | else:
188 | self.pushResult(str(title), password+' ('+username+') ('+timestamp+')')
189 |
190 | # if this is the encrypted password history attribute -> try to parse Native LAPS format
191 | elif(len(value) > 0 and
192 | (str(attribute) == self.cfgLdapAttributePasswordHistory or (isinstance(self.cfgLdapAttributePasswordHistory, list) and str(attribute) in self.cfgLdapAttributePasswordHistory))
193 | ):
194 | for _value in value.values:
195 | password, username, timestamp = self.parseLapsValue(_value)
196 | if(not username or not password):
197 | self.pushResult(str(title), password)
198 | else:
199 | self.pushResult(str(title), password+' ('+username+') ('+timestamp+')')
200 |
201 | # if this is the expiry date attribute -> format date
202 | elif(str(attribute) == self.cfgLdapAttributePasswordExpiry or (isinstance(self.cfgLdapAttributePasswordExpiry, list) and str(attribute) in self.cfgLdapAttributePasswordExpiry)):
203 | try:
204 | self.pushResult(str(title), str(value)+' ('+str(filetime_to_dt( int(str(value)) ))+')')
205 | except Exception as e:
206 | eprint('Error:', str(e))
207 | self.pushResult(str(title), str(value))
208 |
209 | # display raw value
210 | else:
211 | self.pushResult(str(title), str(value))
212 |
213 | # we are looking at a sub-item of the computer object, e.g. a BitLocker recovery key
214 | else:
215 | for title, attribute in self.GetAttributesAsDict().items():
216 | if(attribute[:4] != 'sub:'): continue
217 | subattribute = str(attribute[4:])
218 | if(subattribute in entry):
219 | self.pushResult(str(title), str(entry[subattribute]))
220 |
221 | dpapiCache = dpapi_ng.KeyCache()
222 | def decryptPassword(self, blob):
223 | lastDecryptionError = ''
224 | for server in self.server.servers:
225 | try:
226 | kerberos_auth = (self.cfgUsername=='' or self.cfgPassword=='')
227 | decrypted = dpapi_ng.ncrypt_unprotect_secret(
228 | blob, server = server.host,
229 | username = None if kerberos_auth else self.cfgUsername,
230 | password = None if kerberos_auth else self.cfgPassword,
231 | cache = self.dpapiCache
232 | )
233 | return decrypted.decode('utf-8').replace("\x00", "")
234 | except Exception as e:
235 | if(lastDecryptionError != str(e)):
236 | self.showInfoDialog('Decryption Error', str(e), icon=QMessageBox.Critical)
237 | lastDecryptionError = str(e)
238 |
239 | def parseLapsValue(self, ldapValue):
240 | try:
241 | # if type is bytes -> try to decrypt
242 | if(type(ldapValue) is bytes):
243 | decryptedValue = self.decryptPassword(ldapValue[16:])
244 | if(decryptedValue): ldapValue = decryptedValue
245 |
246 | # parse Native LAPS JSON
247 | jsonDict = json.loads(ldapValue)
248 | if(not 'n' in jsonDict or not 'p' in jsonDict or not 't' in jsonDict):
249 | raise Exception('Invalid LAPS JSON')
250 | return jsonDict['p'], jsonDict['n'], str(filetime_to_dt( int(jsonDict['t'], 16) ))
251 |
252 | except Exception as e:
253 | # directly use LDAP value as password (Legacy LAPS)
254 | return ldapValue, None, None
255 |
256 | dctResult = []
257 | def pushResult(self, attribute, value):
258 | self.dctResult.append({'title':attribute, 'value':value})
259 |
260 | def printResult(self, tsv=False):
261 | if(tsv):
262 | displayValues = []
263 | for attributeValue in self.dctResult:
264 | displayValues.append(attributeValue['value'])
265 | print("\t".join(displayValues))
266 | else:
267 | maxTitleLen = 1
268 | for attributeValue in self.dctResult:
269 | maxTitleLen = max(maxTitleLen, len(attributeValue['title']))
270 | for attributeValue in self.dctResult:
271 | print((attributeValue['title']+':').ljust(maxTitleLen+2)+str(attributeValue['value']))
272 | self.dctResult = []
273 |
274 | def checkCredentialsAndConnect(self):
275 | # ask for server address and domain name if not already set via config file
276 | if(self.cfgDomain == None):
277 | item = input('♕ Domain Name (e.g. example.com, leave empty to try auto discovery): ')
278 | if item != None:
279 | self.cfgDomain = item
280 | self.server = None
281 | if(len(self.cfgServer) == 0):
282 | # query domain controllers by dns lookup
283 | searchDomain = '.'+self.cfgDomain if self.cfgDomain!='' else ''
284 | try:
285 | res = resolver.resolve(qname='_ldap._tcp'+searchDomain, rdtype=rdatatype.SRV, lifetime=10, search=True)
286 | for srv in res.rrset:
287 | serverEntry = {
288 | # strip the trailing . from the dns resolver for certificate verification reasons.
289 | 'address': str(srv.target).rstrip('.'),
290 | 'port': srv.port,
291 | 'ssl': (srv.port == 636),
292 | 'auto-discovered': True
293 | }
294 | print('DNS auto discovery found server: '+json.dumps(serverEntry))
295 | self.cfgServer.append(serverEntry)
296 | except Exception as e: print('DNS auto discovery failed: '+str(e))
297 | # ask user to enter server names if auto discovery was not successful
298 | if(len(self.cfgServer) == 0):
299 | item = input('💻 LDAP Server Address: ')
300 | if item and item.strip() != '':
301 | self.cfgServer.append({
302 | 'address': item,
303 | 'port': 389,
304 | 'ssl': False
305 | })
306 | self.server = None
307 | self.SaveSettings()
308 |
309 | # disable STARTTLS if SSL is used (otherwise, ldap3 will try to do STARTTLS on port 636)
310 | if(len(self.cfgServer) > 0 and self.cfgServer[0]['ssl'] == True):
311 | self.cfgUseStartTls = False
312 |
313 | # establish server connection
314 | if(self.server == None):
315 | try:
316 | serverArray = []
317 | for server in self.cfgServer:
318 | port = server['port']
319 | if('gc-port' in server):
320 | port = server['gc-port']
321 | self.gcModeOn = True
322 | serverArray.append(ldap3.Server(server['address'], port=port, use_ssl=server['ssl'], tls=self.tlsSettings, get_info=ldap3.ALL))
323 | self.server = ldap3.ServerPool(serverArray, ldap3.FIRST, active=2, exhaust=True)
324 | except Exception as e:
325 | print('Error connecting to LDAP server: ', str(e))
326 | return False
327 |
328 | # try to bind to server via Kerberos
329 | try:
330 | if(self.cfgUseKerberos):
331 | self.connection = ldap3.Connection(
332 | self.server,
333 | authentication=ldap3.SASL,
334 | sasl_mechanism=ldap3.GSSAPI,
335 | auto_referrals=True,
336 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
337 | )
338 | if(self.cfgUseStartTls): self.connection.start_tls()
339 | return True # return if connection created successfully
340 | except Exception as e:
341 | print('Unable to connect via Kerberos: '+str(e))
342 | if(isinstance(e, ldap3.core.exceptions.LDAPServerPoolExhaustedError)):
343 | raise Exception('Unable to connect to any of your LDAP servers')
344 |
345 | # ask for username and password for SIMPLE bind
346 | if(self.cfgUsername == ''):
347 | defaultUsername = proposeUsername(self.cfgDomain)
348 | item = input('👤 Username ['+defaultUsername+']: ') or defaultUsername
349 | if item and item.strip() != '':
350 | self.cfgUsername = item
351 | self.connection = None
352 | else: return False
353 | if(self.cfgPassword == ''):
354 | item = getpass.getpass('🔑 Password for »'+self.cfgUsername+'«: ')
355 | if item and item.strip() != '':
356 | self.cfgPassword = item
357 | self.connection = None
358 | else: return False
359 | self.SaveSettings()
360 |
361 | # try to bind to server with username and password
362 | try:
363 | self.connection = ldap3.Connection(
364 | self.server,
365 | user=self.cfgUsername,
366 | password=self.cfgPassword,
367 | authentication=ldap3.SIMPLE,
368 | auto_referrals=True,
369 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
370 | )
371 | if(self.cfgUseStartTls): self.connection.start_tls()
372 | print('') # separate user input from results by newline
373 | except Exception as e:
374 | if(isinstance(e, ldap3.core.exceptions.LDAPServerPoolExhaustedError)):
375 | raise Exception('Unable to connect to any of your LDAP servers')
376 | self.cfgUsername = ''
377 | self.cfgPassword = ''
378 | print('Error binding to LDAP server: ', str(e))
379 | return False
380 |
381 | return True
382 |
383 | def reconnectForAttributeQuery(self):
384 | # global catalog was not used for search - we can use the same connection for attribute query
385 | if(not self.gcModeOn): return True
386 | # global catalog was used for search (this buddy is read only and not all attributes are replicated into it)
387 | # -> that's why we need to establish a new connection to the "normal" LDAP port
388 | # LDAP referrals to the correct (sub)domain controller is handled automatically by ldap3
389 | serverArray = []
390 | for server in self.cfgServer:
391 | serverArray.append(ldap3.Server(server['address'], port=server['port'], use_ssl=server['ssl'], tls=self.tlsSettings, get_info=ldap3.ALL))
392 | server = ldap3.ServerPool(serverArray, ldap3.FIRST, active=True, exhaust=True)
393 | # try to bind to server via Kerberos
394 | try:
395 | if(self.cfgUseKerberos):
396 | self.connection = ldap3.Connection(server,
397 | authentication=ldap3.SASL,
398 | sasl_mechanism=ldap3.GSSAPI,
399 | auto_referrals=True,
400 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
401 | )
402 | if(self.cfgUseStartTls): self.connection.start_tls()
403 | return True
404 | except Exception as e:
405 | print('Unable to connect via Kerberos: '+str(e))
406 | # try to bind to server with username and password
407 | try:
408 | self.connection = ldap3.Connection(server,
409 | user=self.cfgUsername,
410 | password=self.cfgPassword,
411 | authentication=ldap3.SIMPLE,
412 | auto_referrals=True,
413 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
414 | )
415 | if(self.cfgUseStartTls): self.connection.start_tls()
416 | return True
417 | except Exception as e:
418 | print('Error binding to LDAP server: '+str(e))
419 | return False
420 |
421 | def createLdapBase(self, conn):
422 | if self.cfgDomain:
423 | # convert FQDN "example.com" to LDAP path notation "DC=example,DC=com"
424 | search_base = ''
425 | base = self.cfgDomain.split('.')
426 | for b in base:
427 | search_base += 'DC=' + b + ','
428 | return search_base[:-1]
429 | elif conn.server.info and 'defaultNamingContext' in conn.server.info.raw:
430 | return conn.server.info.raw['defaultNamingContext'][0].decode('utf-8')
431 | else:
432 | raise Exception('Could not create LDAP search base: reading defaultNamingContext from LDAP directory failed and no domain given.')
433 |
434 | def GetConnectionString(self):
435 | return str(self.connection.server.host)+' '+str(self.connection.user)
436 |
437 | def LoadSettings(self):
438 | if(not path.isdir(self.cfgDir)):
439 | makedirs(self.cfgDir, exist_ok=True)
440 | # protect temporary .remmina file by limiting access to our config folder
441 | if(self.PLATFORM == 'linux'): os.chmod(self.cfgDir, 0o700)
442 |
443 | dctPresetSettings = {}
444 | dctUserSettings = {}
445 | cfgJson = {}
446 |
447 | try:
448 | if(path.isfile(self.cfgPath)):
449 | with open(self.cfgPath) as f:
450 | dctUserSettings = json.load(f)
451 | cfgJson = dctUserSettings
452 | if(path.isfile(self.cfgPresetPath)):
453 | with open(self.cfgPresetPath) as f:
454 | dctPresetSettings = json.load(f)
455 | # use preset config if version is higher or user settings are empty
456 | if(dctPresetSettings.get('version', 0) > dctUserSettings.get('version', 0)
457 | or dctUserSettings == {}):
458 | cfgJson = dctPresetSettings
459 |
460 | self.cfgVersion = cfgJson.get('version', self.cfgVersion)
461 | self.cfgUseKerberos = cfgJson.get('use-kerberos', self.cfgUseKerberos)
462 | self.cfgUseStartTls = cfgJson.get('use-starttls', self.cfgUseStartTls)
463 | self.cfgServer = cfgJson.get('server', self.cfgServer)
464 | self.cfgDomain = cfgJson.get('domain', self.cfgDomain)
465 | self.cfgLdapQuery = cfgJson.get('ldap-query', self.cfgLdapQuery)
466 | self.cfgUsername = cfgJson.get('username', self.cfgUsername)
467 | self.cfgLdapAttributePassword = cfgJson.get('ldap-attribute-password', self.cfgLdapAttributePassword)
468 | self.cfgLdapAttributePasswordExpiry = cfgJson.get('ldap-attribute-password-expiry', self.cfgLdapAttributePasswordExpiry)
469 | self.cfgLdapAttributePasswordHistory = cfgJson.get('ldap-attribute-password-history', self.cfgLdapAttributePasswordHistory)
470 | tmpLdapAttributes = cfgJson.get('ldap-attributes', self.cfgLdapAttributes)
471 | if(isinstance(tmpLdapAttributes, list) or isinstance(tmpLdapAttributes, dict)):
472 | self.cfgLdapAttributes = tmpLdapAttributes
473 | except Exception as e:
474 | print('Error loading settings file: '+str(e))
475 |
476 | def SaveSettings(self):
477 | try:
478 | # do not save auto-discovered servers to config - should be queried every time
479 | saveServers = []
480 | for server in self.cfgServer:
481 | if not server.get('auto-discovered', False):
482 | saveServers.append(server)
483 |
484 | with open(self.cfgPath, 'w') as json_file:
485 | json.dump({
486 | 'version': self.cfgVersion,
487 | 'use-kerberos': self.cfgUseKerberos,
488 | 'use-starttls': self.cfgUseStartTls,
489 | 'server': saveServers,
490 | 'domain': self.cfgDomain,
491 | 'ldap-query': self.cfgLdapQuery,
492 | 'username': self.cfgUsername,
493 | 'ldap-attribute-password': self.cfgLdapAttributePassword,
494 | 'ldap-attribute-password-expiry': self.cfgLdapAttributePasswordExpiry,
495 | 'ldap-attribute-password-history': self.cfgLdapAttributePasswordHistory,
496 | 'ldap-attributes': self.cfgLdapAttributes
497 | }, json_file, indent=4)
498 | except Exception as e:
499 | print('Error saving settings file: '+str(e))
500 |
501 | def eprint(*args, **kwargs):
502 | print(*args, file=sys.stderr, **kwargs)
503 |
504 | def main():
505 | parser = argparse.ArgumentParser(epilog=__copyright__+' '+__author__+' - https://georg-sieber.de')
506 | parser.add_argument('search', default=None, nargs='*', metavar='COMPUTERNAME', help='Search for this computer(s) and display the admin password. Use "*" to display all computer passwords found in LDAP directory. If you omit this parameter, the interactive shell will be started, which allows you to do multiple queries in one session.')
507 | parser.add_argument('-e', '--set-expiry', default=None, metavar='"2020-01-01 00:00:00"', help='Set new expiration date for computer found by search string.')
508 | parser.add_argument('-K', '--no-kerberos', action='store_true', help='Do not use Kerberos authentication if available, ask for LDAP simple bind credentials.')
509 | parser.add_argument('--version', action='store_true', help='Print version and exit.')
510 | args = parser.parse_args()
511 |
512 | cli = LapsCli(False if args.no_kerberos==True else None)
513 |
514 | if(args.version):
515 | return
516 |
517 | # do LDAP search by command line arguments
518 | if(args.search):
519 | validSearches = 0
520 | for term in args.search:
521 | if(term.strip() == '*'):
522 | cli.SearchComputer('*')
523 | return
524 |
525 | if(term.strip() != ''):
526 | validSearches += 1
527 | cli.SearchComputer(term.strip())
528 | if(args.set_expiry and args.set_expiry.strip() != ''):
529 | cli.SetExpiry(args.set_expiry.strip())
530 |
531 | # if at least one computername was given, we do not start the interactive shell
532 | if(validSearches > 0): return
533 |
534 | # do LDAP search by interactive shell input
535 | print('')
536 | print('Welcome to interactive shell. Please enter a computer name to search for.')
537 | print('Parameter --help provides more information.')
538 | while 1:
539 | # get keyboard input
540 | cmd = input('>> ')
541 | if(cmd == 'exit' or cmd == 'quit'):
542 | return
543 | else:
544 | cli.SearchComputer(cmd.strip())
545 |
546 | if __name__ == '__main__':
547 | main()
548 |
--------------------------------------------------------------------------------
/laps-client/laps_client/laps_gui.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | from .__init__ import __title__, __version__, __website__, __author__, __copyright__
5 | from .__init__ import proposeUsername, compileServerUris
6 | from .filetime import dt_to_filetime, filetime_to_dt
7 |
8 | from PyQt6 import QtWidgets, QtGui, QtCore
9 |
10 | from urllib.parse import unquote
11 | from pathlib import Path
12 | from os import path, makedirs, rename
13 | from datetime import datetime
14 | from dns import resolver, rdatatype
15 | from functools import partial
16 | import traceback
17 | import dpapi_ng
18 | import ldap3
19 | import ssl
20 | import json
21 | import sys
22 | import os
23 |
24 |
25 | class LapsAboutWindow(QtWidgets.QDialog):
26 | def __init__(self, *args, **kwargs):
27 | super(LapsAboutWindow, self).__init__(*args, **kwargs)
28 | self.InitUI()
29 |
30 | def InitUI(self):
31 | self.buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.StandardButton.Ok)
32 | self.buttonBox.accepted.connect(self.accept)
33 |
34 | self.layout = QtWidgets.QVBoxLayout(self)
35 |
36 | labelAppName = QtWidgets.QLabel(self)
37 | labelAppName.setText(__title__ + ' GUI Client' + ' v' + __version__)
38 | labelAppName.setStyleSheet('font-weight:bold')
39 | labelAppName.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
40 | self.layout.addWidget(labelAppName)
41 |
42 | labelCopyright = QtWidgets.QLabel(self)
43 | labelCopyright.setText(
44 | '
'
45 | +__copyright__+' '+__author__+''
46 | '
'
47 | '
'
48 | 'GNU General Public License v3.0'
49 | '
'
50 | ''+__website__+''
51 | '
'
52 | '
'
53 | 'If you like LAPS4LINUX please consider
making a donation to support further development.'
54 | '
'
55 | )
56 | labelCopyright.setOpenExternalLinks(True)
57 | labelCopyright.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
58 | self.layout.addWidget(labelCopyright)
59 |
60 | labelDescription = QtWidgets.QLabel(self)
61 | labelDescription.setText(
62 | 'LAPS4LINUX client allows you to query local administrator passwords for LAPS runner managed workstations in your domain from your LDAP (Active Directory) server.'
63 | '\n\n'
64 | 'The LAPS runner periodically sets a new administrator password and saves it into the LDAP directory.'
65 | '\n\n'
66 | 'LAPS was originally developed by Microsoft, this is an unofficial Linux/Unix implementation with some enhancements (e.g. the CLI/GUI client can display additional attributes).'
67 | )
68 | labelDescription.setFixedWidth(450)
69 | labelDescription.setWordWrap(True)
70 | self.layout.addWidget(labelDescription)
71 |
72 | self.layout.addWidget(self.buttonBox)
73 |
74 | self.setLayout(self.layout)
75 | self.setWindowTitle('About')
76 |
77 | class LapsLoginWindow(QtWidgets.QDialog):
78 | def __init__(self, server, username, *args, **kwargs):
79 | super(LapsLoginWindow, self).__init__(*args, **kwargs)
80 |
81 | # window layout
82 | self.buttonBox = QtWidgets.QDialogButtonBox(
83 | QtWidgets.QDialogButtonBox.StandardButton.Ok
84 | | QtWidgets.QDialogButtonBox.StandardButton.Cancel
85 | )
86 | self.buttonBox.accepted.connect(self.accept)
87 | self.buttonBox.rejected.connect(self.reject)
88 |
89 | self.layout = QtWidgets.QGridLayout(self)
90 |
91 | self.lblDescription = QtWidgets.QLabel('Please enter the credentials which should be used to connect to:\n'+server)
92 | self.layout.addWidget(self.lblDescription, 0, 0, 1, 2)
93 |
94 | self.lblUsername = QtWidgets.QLabel('Username')
95 | self.layout.addWidget(self.lblUsername, 1, 0)
96 | self.txtUsername = QtWidgets.QLineEdit()
97 | self.txtUsername.setText(username)
98 | self.layout.addWidget(self.txtUsername, 1, 1, 1, 2)
99 |
100 | self.lblPassword = QtWidgets.QLabel('Password')
101 | self.layout.addWidget(self.lblPassword, 2, 0)
102 | self.txtPassword = QtWidgets.QLineEdit()
103 | self.txtPassword.setEchoMode(QtWidgets.QLineEdit.EchoMode.Password)
104 | self.layout.addWidget(self.txtPassword, 2, 1, 1, 2)
105 |
106 | self.layout.addWidget(self.buttonBox, 3, 1, 1, 2)
107 | self.setLayout(self.layout)
108 |
109 | # window properties
110 | self.setWindowTitle('LDAP Bind Credentials')
111 | self.resize(350, 150)
112 | #self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False)
113 |
114 | if(self.txtUsername.text() != ''):
115 | self.txtPassword.setFocus()
116 |
117 | class LapsBarcodeWindow(QtWidgets.QDialog):
118 | def __init__(self, title, value, img, *args, **kwargs):
119 | super(LapsBarcodeWindow, self).__init__(*args, **kwargs)
120 | self.title = title
121 | self.value = value
122 | self.img = img
123 | self.InitUI()
124 |
125 | def InitUI(self):
126 | parentWidget = self.parentWidget()
127 |
128 | # Menubar
129 | mainMenu = QtWidgets.QMenuBar(self)
130 | fileMenu = mainMenu.addMenu('&File')
131 | saveAction = QtGui.QAction('&Save image', self)
132 | saveAction.setShortcut('F2')
133 | saveAction.triggered.connect(self.OnClickSave)
134 | fileMenu.addAction(saveAction)
135 | fileMenu.addSeparator()
136 | closeAction = QtGui.QAction('&Close', self)
137 | closeAction.triggered.connect(self.OnClickClose)
138 | fileMenu.addAction(closeAction)
139 |
140 | self.layout = QtWidgets.QVBoxLayout()
141 | self.layout.setContentsMargins(20, 50, 20, 20)
142 |
143 | if(self.img.mode == '1'):
144 | self.img = self.img.convert('RGBA')
145 | img_bytes = self.img.tobytes('raw', 'RGBA')
146 | labelImage = QtWidgets.QLabel(self)
147 | c = QtGui.QCursor(QtCore.Qt.CursorShape.BlankCursor)
148 | labelImage.setCursor(c)
149 | labelImage.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage(img_bytes, self.img.size[0], self.img.size[1], QtGui.QImage.Format.Format_RGBA8888)))
150 | labelImage.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
151 | self.layout.addWidget(labelImage)
152 |
153 | labelText = QtWidgets.QLabel(self)
154 | labelText.setText(self.value)
155 | labelText.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
156 | labelText.setFont(parentWidget.textBoxFont)
157 | self.layout.addWidget(labelText)
158 |
159 | self.setLayout(self.layout)
160 | self.setWindowTitle(self.title)
161 |
162 | def OnClickSave(self):
163 | fileName, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save image', self.title+'.png', 'PNG Files (*.png);;All Files (*.*)')
164 | if(fileName):
165 | self.img.save(fileName)
166 |
167 | def OnClickClose(self):
168 | self.close()
169 |
170 | class LapsCalendarWindow(QtWidgets.QDialog):
171 | def __init__(self, *args, **kwargs):
172 | super(LapsCalendarWindow, self).__init__(*args, **kwargs)
173 | self.InitUI()
174 |
175 | def InitUI(self):
176 | self.buttonBox = QtWidgets.QDialogButtonBox(
177 | QtWidgets.QDialogButtonBox.StandardButton.Ok
178 | | QtWidgets.QDialogButtonBox.StandardButton.Cancel
179 | )
180 | self.buttonBox.accepted.connect(self.OnClickAccept)
181 | self.buttonBox.rejected.connect(self.OnClickReject)
182 |
183 | self.layout = QtWidgets.QVBoxLayout(self)
184 |
185 | self.cwNewExpirationTime = QtWidgets.QCalendarWidget()
186 | self.layout.addWidget(self.cwNewExpirationTime)
187 |
188 | self.layout.addWidget(self.buttonBox)
189 |
190 | self.setLayout(self.layout)
191 | self.setWindowTitle('Set New Expiration Date')
192 |
193 | def OnClickAccept(self):
194 | parentWidget = self.parentWidget()
195 |
196 | # check if dn of target computer object is known
197 | if parentWidget.tmpDn.strip() == '': return
198 |
199 | try:
200 | if isinstance(parentWidget.cfgLdapAttributePasswordExpiry, list) and len(parentWidget.cfgLdapAttributePasswordExpiry) > 0:
201 | attributeExpirationDate = parentWidget.cfgLdapAttributePasswordExpiry[0]
202 | else:
203 | attributeExpirationDate = str(parentWidget.cfgLdapAttributePasswordExpiry)
204 |
205 | # calc new time
206 | newExpirationDate = datetime.combine(self.cwNewExpirationTime.selectedDate().toPyDate(), datetime.min.time())
207 | newExpirationDateTime = dt_to_filetime(newExpirationDate)
208 | print('new expiration time: '+str(newExpirationDateTime))
209 |
210 | # start LDAP modify
211 | parentWidget.connection.modify(parentWidget.tmpDn, { attributeExpirationDate: [(ldap3.MODIFY_REPLACE, [str(newExpirationDateTime)])] })
212 | if parentWidget.connection.result['result'] == 0:
213 | parentWidget.showInfoDialog('Success',
214 | 'Expiration date successfully changed to '+str(newExpirationDate)+'.',
215 | parentWidget.tmpDn+' ('+parentWidget.GetConnectionString()+')'
216 | )
217 | # update values in main window
218 | parentWidget.OnClickSearch(None)
219 | self.close()
220 | else:
221 | parentWidget.showInfoDialog('Error',
222 | 'Unable to change expiration date to '+str(newExpirationDateTime)+'.'
223 | +'\n\n'+str(parentWidget.connection.result['message']), parentWidget.tmpDn+' ('+parentWidget.GetConnectionString()+')',
224 | icon=QtWidgets.QMessageBox.Icon.Critical
225 | )
226 |
227 | except Exception as e:
228 | # display error
229 | parentWidget.showInfoDialog('Error setting new expiration date', str(e), icon=QtWidgets.QMessageBox.Icon.Critical)
230 | # reset connection
231 | parentWidget.server = None
232 | parentWidget.connection = None
233 |
234 | def OnClickReject(self):
235 | self.close()
236 |
237 | class LapsPlainTextEdit(QtWidgets.QPlainTextEdit):
238 | # default sizeHint of (256,192) is too large for our password history
239 | def sizeHint(self):
240 | return QtCore.QSize(200, 90)
241 |
242 | class LapsMainWindow(QtWidgets.QMainWindow):
243 | PLATFORM = sys.platform.lower()
244 |
245 | PROTOCOL_SCHEME = 'laps://'
246 | PRODUCT_ICON = 'laps.png'
247 | PRODUCT_ICON_PATH = '/usr/share/pixmaps'
248 |
249 | tlsSettings = ldap3.Tls(validate=ssl.CERT_REQUIRED)
250 |
251 | gcModeOn = False
252 | server = None
253 | connection = None
254 | tmpDn = ''
255 | currentComputerName = ''
256 |
257 | cfgPresetDirWindows = path.dirname(sys.executable) if getattr(sys, 'frozen', False) else sys.path[0]
258 | cfgPresetDirUnix = '/etc'
259 | cfgPresetFile = 'laps-client.json'
260 | cfgPresetPath = (cfgPresetDirWindows if PLATFORM=='win32' else cfgPresetDirUnix)+'/'+cfgPresetFile
261 |
262 | cfgDir = str(Path.home())+'/.config/laps-client'
263 | cfgPath = cfgDir+'/settings.json'
264 | cfgPathRemmina = cfgDir+'/laps.remmina'
265 | cfgVersion = 0
266 | cfgUseKerberos = True
267 | cfgUseStartTls = True
268 | cfgServer = []
269 | cfgDomain = None
270 | cfgLdapQuery = '(&(objectClass=computer)(cn=%1))'
271 | cfgUsername = ''
272 | cfgPassword = ''
273 | cfgLdapAttributes = {
274 | 'Operating System': 'operatingSystem',
275 | 'Administrator Password': ['msLAPS-EncryptedPassword', 'msLAPS-Password', 'ms-Mcs-AdmPwd'],
276 | 'Password Expiration Date': ['msLAPS-PasswordExpirationTime', 'ms-Mcs-AdmPwdExpirationTime'],
277 | 'Administrator Password History': 'msLAPS-EncryptedPasswordHistory'
278 | }
279 | cfgLdapAttributePassword = ['msLAPS-EncryptedPassword', 'msLAPS-Password', 'ms-Mcs-AdmPwd']
280 | cfgLdapAttributePasswordExpiry = ['msLAPS-PasswordExpirationTime', 'ms-Mcs-AdmPwdExpirationTime']
281 | cfgLdapAttributePasswordHistory = 'msLAPS-EncryptedPasswordHistory'
282 | cfgConnectUsername = 'administrator'
283 | cfgUseAutotypeEnter = False
284 | refLdapAttributesTextBoxes = {}
285 |
286 |
287 | def __init__(self):
288 | super(LapsMainWindow, self).__init__()
289 | self.LoadSettings()
290 | self.InitUI()
291 |
292 | def InitUI(self):
293 | # Icon Selection
294 | if(getattr(sys, 'frozen', False)):
295 | # included via pyinstaller (Windows & macOS)
296 | self.PRODUCT_ICON_PATH = sys._MEIPASS
297 | self.iconPath = path.join(self.PRODUCT_ICON_PATH, self.PRODUCT_ICON)
298 | if(path.exists(self.iconPath)):
299 | self.icon = QtGui.QIcon(self.iconPath)
300 | self.setWindowIcon(self.icon)
301 |
302 | # Menubar
303 | mainMenu = self.menuBar()
304 |
305 | # File Menu
306 | fileMenu = mainMenu.addMenu('&File')
307 |
308 | searchAction = QtGui.QAction('&Search', self)
309 | searchAction.setShortcut('F2')
310 | searchAction.triggered.connect(self.OnClickSearch)
311 | fileMenu.addAction(searchAction)
312 | if(self.cfgLdapAttributePasswordExpiry):
313 | setExpirationDateAction = QtGui.QAction('Set &Expiration', self)
314 | setExpirationDateAction.setShortcut('F3')
315 | setExpirationDateAction.triggered.connect(self.OnClickSetExpiry)
316 | fileMenu.addAction(setExpirationDateAction)
317 | fileMenu.addSeparator()
318 | kerberosAction = QtGui.QAction('&Kerberos Authentication', self)
319 | kerberosAction.setShortcut('Ctrl+K')
320 | kerberosAction.setCheckable(True)
321 | kerberosAction.setChecked(self.cfgUseKerberos)
322 | kerberosAction.triggered.connect(self.OnClickKerberos)
323 | fileMenu.addAction(kerberosAction)
324 | fileMenu.addSeparator()
325 | quitAction = QtGui.QAction('&Quit', self)
326 | quitAction.setShortcut('Ctrl+Q')
327 | quitAction.triggered.connect(self.OnQuit)
328 | fileMenu.addAction(quitAction)
329 |
330 | # Connection Menu
331 | connectMenu = mainMenu.addMenu('&Connect')
332 |
333 | rdpAction = QtGui.QAction('&RDP', self)
334 | rdpAction.setShortcut('F5')
335 | rdpAction.triggered.connect(lambda: self.RemoteConnection('RDP'))
336 | connectMenu.addAction(rdpAction)
337 | sshAction = QtGui.QAction('&SSH', self)
338 | sshAction.setShortcut('F6')
339 | sshAction.triggered.connect(lambda: self.RemoteConnection('SSH'))
340 | connectMenu.addAction(sshAction)
341 | connectMenu.addSeparator()
342 | autotypeCodeAction = QtGui.QAction('&Autotype QR code', self)
343 | autotypeCodeAction.setShortcut('F7')
344 | autotypeCodeAction.triggered.connect(self.OnClickAutotypeCode)
345 | connectMenu.addAction(autotypeCodeAction)
346 | autotypeSeparatorAction = QtGui.QAction('Enter instead of Tab', self)
347 | autotypeSeparatorAction.setCheckable(True)
348 | autotypeSeparatorAction.setChecked(self.cfgUseAutotypeEnter)
349 | autotypeSeparatorAction.triggered.connect(self.OnClickAutotypeEnter)
350 | connectMenu.addAction(autotypeSeparatorAction)
351 |
352 | # Help Menu
353 | helpMenu = mainMenu.addMenu('&Help')
354 |
355 | aboutAction = QtGui.QAction('&About', self)
356 | aboutAction.setShortcut('F1')
357 | aboutAction.triggered.connect(self.OnOpenAboutDialog)
358 | helpMenu.addAction(aboutAction)
359 |
360 | # Statusbar
361 | self.statusBar = self.statusBar()
362 |
363 | # Window Content
364 | grid = QtWidgets.QGridLayout()
365 | gridLine = 0
366 |
367 | self.lblSearchComputer = QtWidgets.QLabel('Computer Name')
368 | grid.addWidget(self.lblSearchComputer, gridLine, 0)
369 | gridLine += 1
370 | self.txtSearchComputer = QtWidgets.QLineEdit()
371 | self.txtSearchComputer.returnPressed.connect(self.OnReturnSearch)
372 | self.txtSearchComputer.contextMenuEvent = partial(self.OnContextMenu, self.txtSearchComputer)
373 | grid.addWidget(self.txtSearchComputer, gridLine, 0)
374 | self.btnSearchComputer = QtWidgets.QPushButton('Search')
375 | self.btnSearchComputer.clicked.connect(self.OnClickSearch)
376 | grid.addWidget(self.btnSearchComputer, gridLine, 1)
377 | gridLine += 1
378 |
379 | self.btnSetExpirationTime = QtWidgets.QPushButton('Set')
380 | self.btnSetExpirationTime.setEnabled(False)
381 | self.btnSetExpirationTime.clicked.connect(self.OnClickSetExpiry)
382 |
383 | for title, attribute in self.GetAttributesAsDict().items():
384 | # create label
385 | lblAdditionalAttribute = QtWidgets.QLabel(str(title))
386 | grid.addWidget(lblAdditionalAttribute, gridLine, 0)
387 | gridLine += 1
388 |
389 | # instantiate single or multiline textbox
390 | if(attribute == self.cfgLdapAttributePasswordHistory
391 | or (isinstance(self.cfgLdapAttributePasswordHistory, list) and attribute in self.cfgLdapAttributePasswordHistory)):
392 | txtAdditionalAttribute = LapsPlainTextEdit()
393 | txtAdditionalAttribute.setLineWrapMode(QtWidgets.QPlainTextEdit.LineWrapMode.NoWrap)
394 | else:
395 | txtAdditionalAttribute = QtWidgets.QLineEdit()
396 | txtAdditionalAttribute.setReadOnly(True)
397 | txtAdditionalAttribute.contextMenuEvent = partial(self.OnContextMenu, txtAdditionalAttribute)
398 |
399 | # set easy readable font
400 | if(self.PLATFORM == 'win32'):
401 | self.textBoxFont = QtGui.QFont('Consolas', 14)
402 | self.textBoxFont.setBold(True)
403 | else:
404 | self.textBoxFont = QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.SystemFont.FixedFont)
405 | self.textBoxFont.setPointSize(18 if self.PLATFORM=='darwin' else 14)
406 | txtAdditionalAttribute.setFont(self.textBoxFont)
407 |
408 | # add textbox to layout
409 | grid.addWidget(txtAdditionalAttribute, gridLine, 0)
410 | self.refLdapAttributesTextBoxes[str(title)] = txtAdditionalAttribute
411 |
412 | # create copy/set button
413 | if(attribute == self.cfgLdapAttributePasswordExpiry
414 | or (isinstance(self.cfgLdapAttributePasswordExpiry, list) and attribute in self.cfgLdapAttributePasswordExpiry)):
415 | grid.addWidget(self.btnSetExpirationTime, gridLine, 1)
416 | else:
417 | btnCopy = QtWidgets.QPushButton('Copy')
418 | btnCopy.clicked.connect(partial(self.OnClickCopy, txtAdditionalAttribute))
419 | grid.addWidget(btnCopy, gridLine, 1)
420 | gridLine += 1
421 |
422 | widget = QtWidgets.QWidget(self)
423 | widget.setLayout(grid)
424 | self.setCentralWidget(widget)
425 |
426 | # Window Settings
427 | self.setMinimumSize(480, 300)
428 | self.setWindowTitle(__title__)
429 | self.statusBar.showMessage('Settings file: '+self.cfgPath)
430 |
431 | # Handle Parameter - Automatic Search
432 | urlToHandle = None
433 | for arg in sys.argv:
434 | if(arg.startswith(self.PROTOCOL_SCHEME)):
435 | urlToHandle = arg
436 | if(urlToHandle != None):
437 | print('Handle '+urlToHandle)
438 | protocolPayload = unquote(urlToHandle).replace(self.PROTOCOL_SCHEME, '').strip(' /')
439 | self.txtSearchComputer.setText(protocolPayload)
440 | self.OnClickSearch(None)
441 |
442 | def GetAttributesAsDict(self):
443 | finalDict = {}
444 | if(isinstance(self.cfgLdapAttributes, list)):
445 | for attribute in self.cfgLdapAttributes:
446 | finalDict[attribute] = attribute
447 | elif(isinstance(self.cfgLdapAttributes, dict)):
448 | for title, attribute in self.cfgLdapAttributes.items():
449 | finalDict[str(title)] = attribute
450 | return finalDict
451 |
452 | def OnQuit(self, e):
453 | sys.exit()
454 |
455 | def OnContextMenu(self, lineEdit, e):
456 | menu = lineEdit.createStandardContextMenu()
457 | qrAction = QtGui.QAction('Show as QR code', self)
458 | qrAction.triggered.connect(lambda: self.OnClickShowAsCode(lineEdit, 'qr'))
459 | menu.addAction(qrAction)
460 | barcodeAction = QtGui.QAction('Show as barcode', self)
461 | barcodeAction.triggered.connect(lambda: self.OnClickShowAsCode(lineEdit, 'barcode'))
462 | menu.addAction(barcodeAction)
463 | menu.exec(e.globalPos())
464 |
465 | def OnClickShowAsCode(self, lineEdit, code):
466 | if(isinstance(lineEdit, QtWidgets.QPlainTextEdit)):
467 | text = lineEdit.toPlainText()
468 | else:
469 | text = lineEdit.text()
470 | if(not text): return
471 | self.showCode(text, code)
472 |
473 | def OnClickCopy(self, lineEdit, e):
474 | if(isinstance(lineEdit, QtWidgets.QPlainTextEdit)):
475 | text = lineEdit.toPlainText()
476 | else:
477 | text = lineEdit.text()
478 | cb = QtWidgets.QApplication.clipboard()
479 | cb.clear(mode=QtGui.QClipboard.Mode.Clipboard)
480 | cb.setText(text, mode=QtGui.QClipboard.Mode.Clipboard)
481 |
482 | def OnClickKerberos(self, e):
483 | self.cfgUseKerberos = not self.cfgUseKerberos
484 | self.SaveSettings()
485 |
486 | def OnClickAutotypeEnter(self, e):
487 | self.cfgUseAutotypeEnter = not self.cfgUseAutotypeEnter
488 | self.SaveSettings()
489 |
490 | def OnOpenAboutDialog(self, e):
491 | dlg = LapsAboutWindow(self)
492 | dlg.exec()
493 |
494 | def OnReturnSearch(self):
495 | self.OnClickSearch(None)
496 |
497 | def OnClickAutotypeCode(self):
498 | separator = "\t"
499 | if(self.cfgUseAutotypeEnter):
500 | # for Linux login screens (lightdm etc.)
501 | separator = "\n"
502 | text = self.cfgConnectUsername + separator + self.getCurrentPassword()
503 | self.showCode(text, 'qr')
504 |
505 | def showCode(self, text, code):
506 | if(code == 'qr'):
507 | import qrcode
508 | img = qrcode.make(text).get_image()
509 | else:
510 | import barcode
511 | barcode.base.Barcode.default_writer_options['write_text'] = False
512 | img = barcode.Code128(text, writer=barcode.writer.ImageWriter()).render()
513 | if(img):
514 | dlg = LapsBarcodeWindow(self.currentComputerName, text, img, self)
515 | dlg.show()
516 |
517 | def versionTuple(self, v):
518 | return tuple(map(int, (v.split('.'))))
519 |
520 | def prepareEnvironment(self):
521 | # restore library search path for subprocess (modified by PyInstaller)
522 | # see https://pyinstaller.org/en/v6.9.0/common-issues-and-pitfalls.html#launching-external-programs-from-the-frozen-application
523 | sub_env = os.environ.copy()
524 | if('LD_LIBRARY_PATH_ORIG' in sub_env):
525 | sub_env['LD_LIBRARY_PATH'] = sub_env['LD_LIBRARY_PATH_ORIG']
526 | elif('LD_LIBRARY_PATH' in sub_env):
527 | del sub_env['LD_LIBRARY_PATH']
528 | return sub_env
529 |
530 | def getCurrentPassword(self):
531 | password = ''
532 | for title, attribute in self.GetAttributesAsDict().items():
533 | if((isinstance(self.cfgLdapAttributePassword, str) and isinstance(attribute, str) and attribute.upper() == self.cfgLdapAttributePassword.upper())
534 | or attribute == self.cfgLdapAttributePassword):
535 | if(title in self.refLdapAttributesTextBoxes):
536 | password = self.refLdapAttributesTextBoxes[title].text()
537 | return password
538 |
539 | def RemoteConnection(self, protocol):
540 | if(self.txtSearchComputer.text().strip() == ''):
541 | return
542 |
543 | # only available on linux as there is no reasonable way to open remote connections with password on other OSes
544 | if(self.PLATFORM != 'linux'):
545 | self.showInfoDialog('Nope.', 'Only available on non-shitty operating systems.', icon=QtWidgets.QMessageBox.Icon.Warning)
546 | return
547 |
548 | try:
549 | import subprocess, time
550 | from shutil import which
551 |
552 | # check remmina existence and version
553 | if(which('remmina') is None): raise Exception('Remmina is not installed')
554 | newRemmina = False
555 | res = subprocess.run('remmina --version | grep org.remmina.Remmina | cut -d- -f2 | cut -d"(" -f1 | xargs', shell=True, env=self.prepareEnvironment(), stdout=subprocess.PIPE, stdin=subprocess.DEVNULL)
556 | if(self.versionTuple(res.stdout.decode('utf-8')) >= self.versionTuple('1.4.25')):
557 | newRemmina = True
558 |
559 | # get current admin password
560 | password = self.getCurrentPassword()
561 |
562 | # passwords must be encrypted in old remmina connection files using the secret found in remmina.pref
563 | if(not newRemmina):
564 | import base64, configparser
565 | from Cryptodome.Cipher import DES3
566 |
567 | remminaPrefPath = str(Path.home())+'/.remmina/remmina.pref' # older remmina versions
568 | if(not os.path.exists(remminaPrefPath)): remminaPrefPath = str(Path.home())+'/.config/remmina/remmina.pref' # newer remmina versions
569 | if(os.path.exists(remminaPrefPath)):
570 | config = configparser.ConfigParser()
571 | config.read(remminaPrefPath)
572 | if(config.has_section('remmina_pref') and 'secret' in config['remmina_pref'] and config['remmina_pref']['secret'].strip() != ''):
573 | secret = base64.b64decode(config['remmina_pref']['secret'])
574 | padding = chr(0) * (8 - len(password) % 8)
575 | password = base64.b64encode( DES3.new(secret[:24], DES3.MODE_CBC, secret[24:]).encrypt((password+padding).encode("utf8")) ).decode('utf-8')
576 | else:
577 | password = ''
578 | self.statusBar.showMessage('Unable to find secret in remmina_pref')
579 | else:
580 | password = ''
581 | self.statusBar.showMessage('Unable to find remmina.pref')
582 |
583 | # creating remmina files with permissions 400 is currently useless as remmina re-creates the file with 664 on exit with updated settings
584 | # protection is done by limiting access to our config dir
585 | if(os.path.isfile(self.cfgPathRemmina)):
586 | os.unlink(self.cfgPathRemmina)
587 |
588 | if(protocol == 'RDP'):
589 | # default config
590 | remminaConfig = ('[remmina]\n'+
591 | 'name=$$host$$\n'+
592 | 'server=$$host$$\n'+
593 | 'username=$$username$$\n'+
594 | 'password=$$password$$\n'
595 | 'protocol=RDP\n'+
596 | 'scale=2\n'+
597 | 'window_width=1092\n'+
598 | 'window_height=720\n'+
599 | 'colordepth=0\n'+
600 | 'sound=off\n')
601 | # use custom RDP config if provided
602 | cfgPathRemminaTemplate = self.cfgDir+'/rdp.remmina.template'
603 | if(os.path.isfile(cfgPathRemminaTemplate)):
604 | with open(cfgPathRemminaTemplate, 'r') as f:
605 | remminaConfig = f.read()
606 | # write temp remmina config
607 | with open(os.open(self.cfgPathRemmina, os.O_CREAT | os.O_WRONLY, 0o400), 'w') as f:
608 | f.write(
609 | remminaConfig
610 | .replace('$$host$$', self.txtSearchComputer.text())
611 | .replace('$$username$$', self.cfgConnectUsername)
612 | .replace('$$password$$', password)
613 | )
614 | f.close()
615 |
616 | elif(protocol == 'SSH'):
617 | # default config
618 | remminaConfig = ('[remmina]\n'+
619 | 'name=$$host$$\n'+
620 | 'server=$$host$$\n'+
621 | 'username=$$username$$\n'+
622 | 'password=$$password$$\n'
623 | 'protocol=SSH\n')
624 | # use custom SSH config if provided
625 | cfgPathRemminaTemplate = self.cfgDir+'/ssh.remmina.template'
626 | if(os.path.isfile(cfgPathRemminaTemplate)):
627 | with open(cfgPathRemminaTemplate, 'r') as f:
628 | remminaConfig = f.read()
629 | # write temp remmina config
630 | with open(os.open(self.cfgPathRemmina, os.O_CREAT | os.O_WRONLY, 0o400), 'w') as f:
631 | f.write(
632 | remminaConfig
633 | .replace('$$host$$', self.txtSearchComputer.text())
634 | .replace('$$username$$', self.cfgConnectUsername)
635 | .replace('$$password$$', password)
636 | )
637 | f.close()
638 |
639 | time.sleep(0.2)
640 | subprocess.Popen(['remmina', '-c', self.cfgPathRemmina], env=self.prepareEnvironment())
641 | except Exception as e:
642 | # display error
643 | self.statusBar.showMessage(str(e))
644 | print(traceback.format_exc())
645 |
646 | def OnClickSearch(self, e):
647 | # check and escape input
648 | computerName = self.txtSearchComputer.text()
649 | if computerName.strip() == '': return
650 | computerName = ldap3.utils.conv.escape_filter_chars(computerName)
651 |
652 | # ask for credentials
653 | self.btnSearchComputer.setEnabled(False)
654 | if not self.checkCredentialsAndConnect():
655 | self.btnSearchComputer.setEnabled(True)
656 | return
657 |
658 | try:
659 | # clear text boxes
660 | for title, attribute in self.GetAttributesAsDict().items():
661 | textBox = self.refLdapAttributesTextBoxes[str(title)]
662 | self.updateTextboxText(textBox, '')
663 | textBox.setToolTip('')
664 |
665 | # start LDAP search
666 | self.connection.search(
667 | search_base = self.createLdapBase(self.connection),
668 | search_filter = self.cfgLdapQuery.replace('%1', computerName),
669 | attributes = ['cn']
670 | )
671 | for entry in self.connection.entries:
672 | self.statusBar.showMessage('Found: '+entry.entry_dn+' ('+self.GetConnectionString()+')')
673 | self.currentComputerName = str(entry['cn'])
674 | self.setWindowTitle(self.currentComputerName+' - '+__title__)
675 | self.tmpDn = entry.entry_dn
676 | self.queryAttributes()
677 | return
678 |
679 | # no result found
680 | self.statusBar.showMessage('No Result For: '+computerName+' ('+self.GetConnectionString()+')')
681 | except Exception as e:
682 | # display error
683 | self.statusBar.showMessage(str(e))
684 | print(str(e))
685 | # reset connection
686 | self.server = None
687 | self.connection = None
688 |
689 | self.tmpDn = ''
690 | self.btnSetExpirationTime.setEnabled(False)
691 | self.btnSearchComputer.setEnabled(True)
692 |
693 | def OnClickSetExpiry(self, e):
694 | # check if dn of target computer object is known
695 | if self.tmpDn.strip() == '': return
696 |
697 | dlg = LapsCalendarWindow(self)
698 | dlg.exec()
699 |
700 | def queryAttributes(self):
701 | if(not self.reconnectForAttributeQuery()):
702 | self.btnSetExpirationTime.setEnabled(False)
703 | self.btnSearchComputer.setEnabled(True)
704 | return
705 |
706 | # start LDAP search
707 | self.connection.search(
708 | search_base = self.tmpDn,
709 | search_filter = '(objectClass=*)',
710 | attributes = ldap3.ALL_ATTRIBUTES
711 | )
712 | # display result
713 | for entry in self.connection.entries:
714 | # we are looking at the main computer object
715 | if(entry.entry_dn == self.tmpDn):
716 | self.btnSetExpirationTime.setEnabled(True)
717 | self.btnSearchComputer.setEnabled(True)
718 |
719 | # evaluate attributes of interest
720 | for title, attribute in self.GetAttributesAsDict().items():
721 | if(attribute[:4] == 'sub:'): continue
722 | textBox = self.refLdapAttributesTextBoxes[str(title)]
723 | value = None
724 | if(isinstance(attribute, list)):
725 | for _attribute in attribute:
726 | # use first non-empty attribute
727 | if(str(_attribute) in entry and entry[str(_attribute)]):
728 | value = entry[str(_attribute)]
729 | attribute = str(_attribute)
730 | break
731 | elif(str(attribute) in entry):
732 | value = entry[str(attribute)]
733 |
734 | # handle non-existing attributes
735 | if(value == None):
736 | pass
737 |
738 | # if this is the password attribute -> try to parse Native LAPS format
739 | elif(len(value) > 0 and
740 | (str(attribute) == self.cfgLdapAttributePassword or (isinstance(self.cfgLdapAttributePassword, list) and str(attribute) in self.cfgLdapAttributePassword))
741 | ):
742 | password, username, timestamp = self.parseLapsValue(value.values[0])
743 | self.updateTextboxText(textBox, str(password))
744 | if(username and password):
745 | self.cfgConnectUsername = username
746 | textBox.setToolTip(username+', '+timestamp)
747 |
748 | # if this is the encrypted password history attribute -> try to parse Native LAPS format
749 | elif(len(value) > 0 and
750 | (str(attribute) == self.cfgLdapAttributePasswordHistory or (isinstance(self.cfgLdapAttributePasswordHistory, list) and str(attribute) in self.cfgLdapAttributePasswordHistory))
751 | ):
752 | lines = []
753 | for _value in value.values:
754 | password, username, timestamp = self.parseLapsValue(_value)
755 | if(not username or not password):
756 | lines.append(str(password))
757 | else:
758 | lines.append(password+' '+username+' '+timestamp)
759 | self.updateTextboxText(textBox, "\n".join(lines))
760 |
761 | # if this is the expiry date attribute -> format date
762 | elif(str(attribute) == self.cfgLdapAttributePasswordExpiry or (isinstance(self.cfgLdapAttributePasswordExpiry, list) and str(attribute) in self.cfgLdapAttributePasswordExpiry)):
763 | try:
764 | self.updateTextboxText(textBox, str(filetime_to_dt( int(str(value)) )) )
765 | except Exception as e:
766 | print(str(e))
767 | self.updateTextboxText(textBox, str(value))
768 |
769 | # display raw value
770 | else:
771 | self.updateTextboxText(textBox, str(value))
772 |
773 | # we are looking at a sub-item of the computer object, e.g. a BitLocker recovery key
774 | else:
775 | for title, attribute in self.GetAttributesAsDict().items():
776 | textBox = self.refLdapAttributesTextBoxes[str(title)]
777 | if(attribute[:4] != 'sub:'): continue
778 | subattribute = str(attribute[4:])
779 | if(subattribute in entry):
780 | self.updateTextboxText(textBox, str(entry[subattribute]))
781 |
782 | def updateTextboxText(self, textBox, text):
783 | if(isinstance(textBox, QtWidgets.QPlainTextEdit)):
784 | textBox.setPlainText(text)
785 | else:
786 | textBox.setText(text)
787 |
788 | dpapiCache = dpapi_ng.KeyCache()
789 | def decryptPassword(self, blob):
790 | lastDecryptionError = ''
791 | for server in self.server.servers:
792 | try:
793 | kerberos_auth = (self.cfgUsername=='' or self.cfgPassword=='')
794 | decrypted = dpapi_ng.ncrypt_unprotect_secret(
795 | blob, server = server.host,
796 | username = None if kerberos_auth else self.cfgUsername,
797 | password = None if kerberos_auth else self.cfgPassword,
798 | cache = self.dpapiCache
799 | )
800 | return decrypted.decode('utf-8').replace("\x00", "")
801 | except Exception as e:
802 | if(lastDecryptionError != str(e)):
803 | self.showInfoDialog('Decryption Error', str(e), icon=QtWidgets.QMessageBox.Icons.Critical)
804 | lastDecryptionError = str(e)
805 |
806 | def parseLapsValue(self, ldapValue):
807 | try:
808 | # if type is bytes -> try to decrypt
809 | if(type(ldapValue) is bytes):
810 | decryptedValue = self.decryptPassword(ldapValue[16:])
811 | if(decryptedValue): ldapValue = decryptedValue
812 |
813 | # parse Native LAPS JSON
814 | jsonDict = json.loads(ldapValue)
815 | if(not 'n' in jsonDict or not 'p' in jsonDict or not 't' in jsonDict):
816 | raise Exception('Invalid LAPS JSON')
817 | return jsonDict['p'], jsonDict['n'], str(filetime_to_dt( int(jsonDict['t'], 16) ))
818 |
819 | except Exception as e:
820 | # directly use LDAP value as password (Legacy LAPS)
821 | return ldapValue, None, None
822 |
823 | def checkCredentialsAndConnect(self):
824 | # ask for server address and domain name if not already set via config file
825 | if(self.cfgDomain == None):
826 | item, ok = QInputDialog.getText(self, '♕ Domain', 'Please enter your Domain name (e.g. example.com, leave empty to try auto discovery).')
827 | if ok and item != None:
828 | self.cfgDomain = item
829 | self.server = None
830 | else: return False
831 | if(len(self.cfgServer) == 0):
832 | # query domain controllers by dns lookup
833 | searchDomain = '.'+self.cfgDomain if self.cfgDomain!='' else ''
834 | try:
835 | res = resolver.resolve(qname='_ldap._tcp'+searchDomain, rdtype=rdatatype.SRV, lifetime=10, search=True)
836 | for srv in res.rrset:
837 | serverEntry = {
838 | # strip the trailing . from the dns resolver for certificate verification reasons.
839 | 'address': str(srv.target).rstrip('.'),
840 | 'port': srv.port,
841 | 'ssl': (srv.port == 636),
842 | 'auto-discovered': True
843 | }
844 | print('DNS auto discovery found server: '+json.dumps(serverEntry))
845 | self.cfgServer.append(serverEntry)
846 | except Exception as e: print('DNS auto discovery failed: '+str(e))
847 | # ask user to enter server names if auto discovery was not successful
848 | if(len(self.cfgServer) == 0):
849 | item, ok = QInputDialog.getText(self, '💻 Server Address', 'Please enter your LDAP server IP address or DNS name.')
850 | if ok and item:
851 | self.cfgServer.append({
852 | 'address': item,
853 | 'port': 389,
854 | 'ssl': False
855 | })
856 | self.server = None
857 | self.SaveSettings()
858 |
859 | # disable STARTTLS if SSL is used (otherwise, ldap3 will try to do STARTTLS on port 636)
860 | if(len(self.cfgServer) > 0 and self.cfgServer[0]['ssl'] == True):
861 | self.cfgUseStartTls = False
862 |
863 | # establish server connection
864 | if(self.server == None):
865 | try:
866 | serverArray = []
867 | for server in self.cfgServer:
868 | port = server['port']
869 | if('gc-port' in server):
870 | port = server['gc-port']
871 | self.gcModeOn = True
872 | serverArray.append(ldap3.Server(server['address'], port=port, use_ssl=server['ssl'], tls=self.tlsSettings, get_info=ldap3.ALL))
873 | self.server = ldap3.ServerPool(serverArray, ldap3.FIRST, active=2, exhaust=True)
874 | except Exception as e:
875 | self.showInfoDialog('Error connecting to LDAP server', str(e), icon=QtWidgets.QMessageBox.Icon.Critical)
876 | return False
877 |
878 | # try to bind to server via Kerberos
879 | try:
880 | if(self.cfgUseKerberos):
881 | self.connection = ldap3.Connection(
882 | self.server,
883 | authentication=ldap3.SASL,
884 | sasl_mechanism=ldap3.GSSAPI,
885 | auto_referrals=True,
886 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
887 | )
888 | if(self.cfgUseStartTls): self.connection.start_tls()
889 | return True # return if connection created successfully
890 | except Exception as e:
891 | print('Unable to connect via Kerberos: '+str(e))
892 | if(isinstance(e, ldap3.core.exceptions.LDAPServerPoolExhaustedError)):
893 | self.statusBar.showMessage(str(e))
894 | return False
895 |
896 | # ask for username and password for SIMPLE bind
897 | if(self.cfgUsername == '' or self.cfgPassword == ''):
898 | loginWindow = LapsLoginWindow(
899 | username = proposeUsername(self.cfgDomain) if self.cfgUsername == '' else self.cfgUsername,
900 | server = str(compileServerUris(self.cfgServer))
901 | )
902 | if(loginWindow.exec() != QtWidgets.QDialog.DialogCode.Accepted):
903 | return False
904 | self.connection = None
905 | self.cfgUsername = loginWindow.txtUsername.text()
906 | self.cfgPassword = loginWindow.txtPassword.text()
907 | self.SaveSettings()
908 |
909 | # try to bind to server with username and password
910 | try:
911 | self.connection = ldap3.Connection(
912 | self.server,
913 | user=self.cfgUsername,
914 | password=self.cfgPassword,
915 | authentication=ldap3.SIMPLE,
916 | auto_referrals=True,
917 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
918 | )
919 | if(self.cfgUseStartTls): self.connection.start_tls()
920 | except Exception as e:
921 | if(isinstance(e, ldap3.core.exceptions.LDAPServerPoolExhaustedError)):
922 | self.statusBar.showMessage(str(e))
923 | return False
924 | self.cfgPassword = ''
925 | self.showInfoDialog('Error binding to LDAP server', str(e), icon=QtWidgets.QMessageBox.Icon.Critical)
926 | return False
927 |
928 | return True # return if connection created successfully
929 |
930 | def reconnectForAttributeQuery(self):
931 | # global catalog was not used for search - we can use the same connection for attribute query
932 | if(not self.gcModeOn): return True
933 | # global catalog was used for search (this buddy is read only and not all attributes are replicated into it)
934 | # -> that's why we need to establish a new connection to the "normal" LDAP port
935 | # LDAP referrals to the correct (sub)domain controller is handled automatically by ldap3
936 | serverArray = []
937 | for server in self.cfgServer:
938 | serverArray.append(ldap3.Server(server['address'], port=server['port'], use_ssl=server['ssl'], tls=self.tlsSettings, get_info=ldap3.ALL))
939 | server = ldap3.ServerPool(serverArray, ldap3.FIRST, active=True, exhaust=True)
940 | # try to bind to server via Kerberos
941 | try:
942 | if(self.cfgUseKerberos):
943 | self.connection = ldap3.Connection(server,
944 | authentication=ldap3.SASL,
945 | sasl_mechanism=ldap3.GSSAPI,
946 | auto_referrals=True,
947 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
948 | )
949 | if(self.cfgUseStartTls): self.connection.start_tls()
950 | return True
951 | except Exception as e:
952 | print('Unable to connect via Kerberos: '+str(e))
953 | # try to bind to server with username and password
954 | try:
955 | self.connection = ldap3.Connection(server,
956 | user=self.cfgUsername,
957 | password=self.cfgPassword,
958 | authentication=ldap3.SIMPLE,
959 | auto_referrals=True,
960 | auto_bind=(ldap3.AUTO_BIND_TLS_BEFORE_BIND if self.cfgUseStartTls else True)
961 | )
962 | if(self.cfgUseStartTls): self.connection.start_tls()
963 | return True
964 | except Exception as e:
965 | self.showInfoDialog('Error binding to LDAP server', str(e), icon=QtWidgets.QMessageBox.Icon.Critical)
966 | return False
967 |
968 | def createLdapBase(self, conn):
969 | if self.cfgDomain:
970 | # convert FQDN "example.com" to LDAP path notation "DC=example,DC=com"
971 | search_base = ''
972 | base = self.cfgDomain.split('.')
973 | for b in base:
974 | search_base += 'DC=' + b + ','
975 | return search_base[:-1]
976 | elif conn.server.info and 'defaultNamingContext' in conn.server.info.raw:
977 | return conn.server.info.raw['defaultNamingContext'][0].decode('utf-8')
978 | else:
979 | raise Exception('Could not create LDAP search base: reading defaultNamingContext from LDAP directory failed and no domain given.')
980 |
981 | def GetConnectionString(self):
982 | return str(self.connection.server.host)+' '+str(self.connection.user)
983 |
984 | def LoadSettings(self):
985 | if(not path.isdir(self.cfgDir)):
986 | makedirs(self.cfgDir, exist_ok=True)
987 | # protect temporary .remmina file by limiting access to our config folder
988 | if(self.PLATFORM == 'linux'): os.chmod(self.cfgDir, 0o700)
989 |
990 | dctPresetSettings = {}
991 | dctUserSettings = {}
992 | cfgJson = {}
993 |
994 | try:
995 | if(path.isfile(self.cfgPath)):
996 | with open(self.cfgPath) as f:
997 | dctUserSettings = json.load(f)
998 | cfgJson = dctUserSettings
999 | if(path.isfile(self.cfgPresetPath)):
1000 | with open(self.cfgPresetPath) as f:
1001 | dctPresetSettings = json.load(f)
1002 | # use preset config if version is higher or user settings are empty
1003 | if(dctPresetSettings.get('version', 0) > dctUserSettings.get('version', 0)
1004 | or dctUserSettings == {}):
1005 | cfgJson = dctPresetSettings
1006 |
1007 | self.cfgVersion = cfgJson.get('version', self.cfgVersion)
1008 | self.cfgUseKerberos = cfgJson.get('use-kerberos', self.cfgUseKerberos)
1009 | self.cfgUseStartTls = cfgJson.get('use-starttls', self.cfgUseStartTls)
1010 | self.cfgServer = cfgJson.get('server', self.cfgServer)
1011 | self.cfgDomain = cfgJson.get('domain', self.cfgDomain)
1012 | self.cfgLdapQuery = cfgJson.get('ldap-query', self.cfgLdapQuery)
1013 | self.cfgUsername = cfgJson.get('username', self.cfgUsername)
1014 | self.cfgLdapAttributePassword = cfgJson.get('ldap-attribute-password', self.cfgLdapAttributePassword)
1015 | self.cfgLdapAttributePasswordExpiry = cfgJson.get('ldap-attribute-password-expiry', self.cfgLdapAttributePasswordExpiry)
1016 | self.cfgLdapAttributePasswordHistory = cfgJson.get('ldap-attribute-password-history', self.cfgLdapAttributePasswordHistory)
1017 | tmpLdapAttributes = cfgJson.get('ldap-attributes', self.cfgLdapAttributes)
1018 | self.cfgConnectUsername = str(cfgJson.get('connect-username', self.cfgConnectUsername))
1019 | self.cfgUseAutotypeEnter = cfgJson.get('use-autotype-enter', self.cfgUseAutotypeEnter)
1020 | if(isinstance(tmpLdapAttributes, list) or isinstance(tmpLdapAttributes, dict)):
1021 | self.cfgLdapAttributes = tmpLdapAttributes
1022 | except Exception as e:
1023 | self.showInfoDialog('Error loading settings file', str(e), icon=QtWidgets.QMessageBox.Icon.Critical)
1024 |
1025 | def SaveSettings(self):
1026 | try:
1027 | # do not save auto-discovered servers to config - should be queried every time
1028 | saveServers = []
1029 | for server in self.cfgServer:
1030 | if not server.get('auto-discovered', False):
1031 | saveServers.append(server)
1032 |
1033 | with open(self.cfgPath, 'w') as json_file:
1034 | json.dump({
1035 | 'version': self.cfgVersion,
1036 | 'use-kerberos': self.cfgUseKerberos,
1037 | 'use-starttls': self.cfgUseStartTls,
1038 | 'server': saveServers,
1039 | 'domain': self.cfgDomain,
1040 | 'ldap-query': self.cfgLdapQuery,
1041 | 'username': self.cfgUsername,
1042 | 'ldap-attribute-password': self.cfgLdapAttributePassword,
1043 | 'ldap-attribute-password-expiry': self.cfgLdapAttributePasswordExpiry,
1044 | 'ldap-attribute-password-history': self.cfgLdapAttributePasswordHistory,
1045 | 'ldap-attributes': self.cfgLdapAttributes,
1046 | 'connect-username': self.cfgConnectUsername,
1047 | 'use-autotype-enter': self.cfgUseAutotypeEnter,
1048 | }, json_file, indent=4)
1049 | except Exception as e:
1050 | self.showInfoDialog('Error saving settings file', str(e), icon=QtWidgets.QMessageBox.Icon.Critical)
1051 |
1052 | def showInfoDialog(self, title, text, additionalText='', icon=QtWidgets.QMessageBox.Icon.Information):
1053 | print('Dialog:', title, ':', text, ':', additionalText, ':', icon)
1054 | msg = QtWidgets.QMessageBox()
1055 | msg.setIcon(icon)
1056 | msg.setWindowTitle(title)
1057 | msg.setText(text)
1058 | msg.setDetailedText(additionalText)
1059 | msg.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
1060 | retval = msg.exec()
1061 |
1062 | def main():
1063 | # as long as we want to support Debian 11 and Ubuntu 22.04,
1064 | # we need to fall back to X11 Qt Platform Plugin because those
1065 | # distros have a too old libwayland on board, causing a crash
1066 | # "undefined symbol: wl_proxy_marshal_flags"
1067 | if(sys.platform == 'linux'):
1068 | os.environ.setdefault('QT_QPA_PLATFORM', 'xcb')
1069 |
1070 | app = QtWidgets.QApplication(sys.argv)
1071 | window = LapsMainWindow()
1072 | window.show()
1073 | sys.exit(app.exec())
1074 |
1075 | if __name__ == '__main__':
1076 | main()
1077 |
--------------------------------------------------------------------------------
/laps-client/requirements-barcode.txt:
--------------------------------------------------------------------------------
1 | pillow # needed by both QR/barcode
2 |
3 | python-barcode[images]
4 | qrcode
5 |
--------------------------------------------------------------------------------
/laps-client/requirements.txt:
--------------------------------------------------------------------------------
1 | cryptography>=3.1.0
2 | dnspython>=2.0.0
3 | dpapi-ng[kerberos]>=0.2.0
4 | gssapi; sys_platform != "win32" # needs libkrb5-dev
5 | winkerberos; sys_platform == "win32"
6 | ldap3>=2.9.1
7 | pycryptodomex # required only for Remmina connections
8 |
9 | # needs: libxcb-cursor0
10 | PyQt6==6.7.1
11 |
--------------------------------------------------------------------------------
/laps-client/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.command.clean import clean
2 | from distutils import log
3 | from setuptools import setup
4 | import os
5 |
6 | # Get the long description from the README file
7 | here = os.path.abspath(os.path.dirname(__file__))
8 | with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
9 | long_description = f.read()
10 |
11 | setup(
12 | name='laps4linux_client',
13 | version=__import__('laps_client').__version__,
14 | description='View local administrator (LAPS) passwords from your AD/LDAP directory',
15 | long_description=long_description,
16 | long_description_content_type='text/markdown',
17 | install_requires=[i.strip() for i in open('requirements.txt').readlines()],
18 | extras_require={
19 | 'barcode': [i.strip() for i in open('requirements-barcode.txt').readlines()],
20 | },
21 | license=__import__('laps_client').__license__,
22 | author='Georg Sieber',
23 | keywords='laps password administrator ad ldap',
24 | url=__import__('laps_client').__website__,
25 | classifiers=[
26 | 'Development Status :: 5 - Production/Stable',
27 | 'Intended Audience :: System Administrators',
28 | 'Operating System :: POSIX :: Linux',
29 | 'Operating System :: MacOS',
30 | 'Operating System :: Microsoft :: Windows',
31 | 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
32 | 'Programming Language :: Python',
33 | 'Programming Language :: Python :: 3',
34 | ],
35 | packages=['laps_client'],
36 | entry_points={
37 | 'gui_scripts': [
38 | 'laps-gui = laps_client.laps_gui:main',
39 | ],
40 | 'console_scripts': [
41 | 'laps-cli = laps_client.laps_cli:main',
42 | ],
43 | },
44 | platforms=['all'],
45 | #install_requires=[],
46 | #test_suite='tests',
47 | )
48 |
--------------------------------------------------------------------------------
/laps-runner/README.md:
--------------------------------------------------------------------------------
1 | # LAPS4LINUX Runner
2 | The runner is responsible for automatically changing the admin password of a Linux client and updating it in the LDAP directory. This assumes that Kerberos (`krb5-user`) is installed and that the machine is already joined to your domain using Samba's `net ads join`, PBIS' `domainjoin-cli join` or the `adcli join` command (recommended). `realm join` is also supported as it internally also uses adcli resp. Samba.
3 |
4 | A detailed domain join guide is available [on my website](https://georg-sieber.de/?page=blog-linux-im-unternehmen) (attention: only in German).
5 |
6 | The runner should be called periodically via cron ([example](../assets/laps-runner.cron)). This does not mean that the password will be rotated every time the cron job runs - it decides by the expiration time stored in the LDAP directory when the password needs to be changed.
7 |
8 | Please make sure that `usermod` (for changing the password in the local database) is in you crontab `$PATH` (this is the default in Debian and Ubuntu based systems, but may not in other distros).
9 |
10 | ### Installation
11 | It is recommended to use the installation package provided on the [Github releases](https://github.com/schorschii/LAPS4LINUX/releases) page.
12 |
13 | Manual installation in a Python venv:
14 | ```
15 | # install available python modules globally to avoid duplicate install in venv
16 | apt install python3-venv python3-pip python3-setuptools python3-gssapi python3-dnspython krb5-user libkrb5-dev
17 |
18 | python3 -m venv venv --system-site-packages
19 | venv/bin/pip3 install .
20 |
21 | venv/bin/laps-runner
22 | ```
23 |
24 | ### Configuration
25 | Please configure the runner by editing the configuration file `/etc/laps-runner.json`.
26 |
27 |
28 | Configuration Values
29 |
30 | - `server`: Array of domain controllers with items like `{"address": "dc1.example.com", "port": 389, "ssl": false}`. Leave empty for DNS auto discovery.
31 | - `domain`: Your domain name (e.g. `example.com`). Leave empty for DNS auto discovery.
32 | - `ldap-query`: LDAP filter for getting the computer object, default: `(&(objectClass=computer)(cn=%1))`. `%1` is replaced by the computer name.
33 | - `use-starttls`: Boolean which indicates wheter to use StartTLS on unencrypted LDAP connections (requires valid server certificate).
34 | - `client-keytab-file`: The Kerberos keytab file with the machine secret.
35 | - `cred-cache-file`: File where to store the kerberos ticket for the LDAP connection.
36 | - `native-laps`: `true` to store the password as JSON string in the LDAP attribute, as specified by Microsoft (Native LAPS). `false` to store it as plaintext (Legacy LAPS).
37 | - `security-descriptor`: The security descriptor (SID) for pasword encryption (Native LAPS only). Leave empty (set to `null`) to disable encryption. Important: if you enable encryption, you should also change `ldap-attribute-password` to `msLAPS-EncryptedPassword`!
38 | - `history-size`: The amount of password entries to keep in history. If not set or `0`, no password history will be written.
39 | - `ldap-attribute-password`: The LDAP attribute name where to store the generated password. Must be a string, not a list.
40 | - `ldap-attribute-password-history`: The LDAP attribute where to store the password history. Must be a multi-value text field. If empty, no password history will be written.
41 | - `ldap-attribute-password-expiry`: The LDAP attribute where to store the password expiration date. Must be a string, not a list.
42 | - `hostname`: The hostname used for Kerberos ticket creation. Leave empty to use the system's hostname.
43 | - `password-change-user`: The Linux user whose password should be rotated.
44 | - `password-days-valid`: The amount of days how long a password should be valid.
45 | - `password-length`: Determines how long a generated password should be.
46 | - `password-alphabet`: Determines the chars to use for password generation. Can be either just a character string or a list of character strings. In the latter case, the password contains at least one character from each string.
47 | - `hooks`: Dict of commands to execute after password change. The dict key should be a string (displayed in log output) and the value should be an array of parameters. Parameter `$PASSWORD$` and `$USERNAME$` will be replaced accordingly. Have a look at the sample config file for example hooks. You can use this feature to align other passwords with the local admin/root, e.g. your BIOS/UEFI password or the password of local database admin accounts.
48 |
49 | Important:
50 | - If `native-laps` is `false`, you should set `ldap-attribute-password` to `ms-Mcs-AdmPwd` and `ldap-attribute-password-expiry` to `ms-Mcs-AdmPwdExpirationTime`.
51 | - If If `native-laps` is `true` and `security-descriptor` not set or `null`, you should set `ldap-attribute-password` to `msLAPS-Password` and `ldap-attribute-password-expiry` to `msLAPS-PasswordExpirationTime`.
52 | - If If `native-laps` is `true` and `security-descriptor` is set to a valid SID in your domain, you should set `ldap-attribute-password` to `msLAPS-EncryptedPassword` and `ldap-attribute-password-expiry` to `msLAPS-PasswordExpirationTime`.
53 | - While it is technically possible to save the password history unencrypted, Microsoft did not designated this. By default, in Active Directory, the only password history attribute is `msLAPS-EncryptedPasswordHistory`. Therefore, you should only configure the runner to store a password history when using password encryption too.
54 |
55 |
56 | You can call the runner with the `-f` parameter to force updating the password directly after installation. You should do this to check if the runner is working properly.
57 |
58 | ### Automatically Rotate Password After Logout
59 | If LAPS4LINUX should automatically change the password after logout, you need to add the following line into your PAM config. The exact config file depends on your Linux distribution, e.g. `/etc/pam.d/common-session` (use `/etc/pam.d/common-session-noninteractive` if you like to rotate the password on sudo usage too).
60 | ```
61 | session optional pam_exec.so type=close_session seteuid quiet /usr/sbin/laps-runner --pam
62 | ```
63 |
64 | For Ubuntu, you should use a separate PAM config instead: `/usr/share/pam-configs/laps`.
65 | ```
66 | Name: LAPS4LINUX configuration
67 | Default: yes
68 | Priority: 0
69 |
70 | Session-Type: Additional
71 | Session-Interactive-Only: yes
72 | Session:
73 | optional pam_exec.so type=close_session seteuid quiet /usr/sbin/laps-runner-pam
74 | ```
75 | Use `Session-Interactive-Only: no` if you like to rotate the password on sudo usage too.
76 |
77 | Then, run `pam-auth-update` to automatically generate the files under `/etc/pam.d/` with the necessary line for LAPS.
78 |
79 | You can add `login` to the array `pam-services` in the config file if you do not want to change the password on `sudo -i` usage. Since this config option is an array, this allows you to trigger LAPS on multiple, specific PAM service events.
80 |
81 | If you want the runner to wait a certain time after logout until the password should be changed, set `pam-grace-period` in the runner config to the desired number of seconds, e.g. 300 for 5 minutes.
82 |
83 | ### Hostnames Longer Than 15 Characters
84 | Computer objects in the Microsoft Active Directory can not be longer than 15 characters. If you join a computer with a longer hostname, it will be registered with a different "short name". You have to enter this short name in the config file (setting `hostname`) in order to make the Kerberos authentication work. You can find out the short name by inspecting your keytab: `sudo klist -k /etc/krb5.keytab`.
85 |
86 | Set the `hostname` option to `null` (default) to use the system's normal host name.
87 |
88 | ### Troubleshooting
89 | If the script throws an error like `kinit -k -c /tmp/laps.temp SERVER$ returned non-zero exit code 1`, please check what happens when you execute the following commands manually on the command line.
90 | ```
91 | sudo kinit -k -c /tmp/laps.temp COMPUTERNAME$
92 | sudo klist -c /tmp/laps.temp
93 | ```
94 | Please replace COMPUTERNAME with your hostname, but do not forget the trailing dollar sign.
95 |
96 | ## Support
97 | If you like LAPS4LINUX please consider making a donation using the sponsor button on [GitHub](https://github.com/schorschii/LAPS4LINUX) to support further development.
98 |
99 | You can hire me for commercial support or adjustments for this project. Please [contact me](https://georg-sieber.de/?page=impressum) if you are interested.
100 |
--------------------------------------------------------------------------------
/laps-runner/laps-runner-pam:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | nohup /usr/sbin/laps-runner --pam &
4 |
--------------------------------------------------------------------------------
/laps-runner/laps-runner-script.py:
--------------------------------------------------------------------------------
1 | import laps_runner.laps_runner
2 | laps_runner.laps_runner.main()
3 |
--------------------------------------------------------------------------------
/laps-runner/laps-runner.json.example:
--------------------------------------------------------------------------------
1 | {
2 | "COMMENT": "If you want to use static domain and servers, please remove the '-EXAMPLE' from the following setting items and enter your custom values. Otherwise, laps-runner will try to auto discover the settings via DNS.",
3 | "server-EXAMPLE": [
4 | {
5 | "address": "dc1.example.com",
6 | "port": 389,
7 | "ssl": false
8 | },
9 | {
10 | "address": "dc2.example.com",
11 | "port": 389,
12 | "ssl": false
13 | },
14 | {
15 | "address": "dc3.example.com",
16 | "port": 389,
17 | "ssl": false
18 | }
19 | ],
20 | "use-starttls": true,
21 | "domain-EXAMPLE": "example.com",
22 | "ldap-query-EXAMPLE": "(&(objectClass=computer)(cn=%1))",
23 |
24 | "cred-cache-file": "/tmp/laps.temp",
25 | "client-keytab-file": "/etc/krb5.keytab",
26 |
27 | "native-laps": true,
28 | "security-descriptor": null,
29 | "history-size": 0,
30 | "ldap-attribute-password": "msLAPS-Password",
31 | "ldap-attribute-password-history": "msLAPS-EncryptedPasswordHistory",
32 | "ldap-attribute-password-expiry": "msLAPS-PasswordExpirationTime",
33 |
34 | "hostname": null,
35 |
36 | "password-change-user": "root",
37 | "password-days-valid": 30,
38 | "password-length": 15,
39 | "password-alphabet": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
40 |
41 | "pam-services-EXAMPLE": ["login"],
42 | "pam-grace-period-EXAMPLE": 300,
43 |
44 | "hooks-EXAMPLE": {
45 | "ipmitool": ["ipmitool", "user", "set", "password", "$PASSWORD$"],
46 | "influx": ["influx", "user", "password", "--name", "$USERNAME$", "--password", "$PASSWORD$"]
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/laps-runner/laps-runner.linux.spec:
--------------------------------------------------------------------------------
1 | # -*- mode: python ; coding: utf-8 -*-
2 | from PyInstaller.utils.hooks import collect_submodules
3 |
4 | hiddenimports = []
5 | hiddenimports += collect_submodules('gssapi.raw')
6 |
7 | block_cipher = None
8 |
9 | a = Analysis(
10 | ['laps-runner-script.py'],
11 | pathex=['.'],
12 | binaries=[],
13 | datas=[],
14 | hiddenimports=hiddenimports,
15 | hookspath=[],
16 | runtime_hooks=[],
17 | excludes=[],
18 | cipher=block_cipher,
19 | noarchive=False,
20 | optimize=0,
21 | )
22 | pyz = PYZ(a.pure)
23 |
24 | exe = EXE(pyz, a.scripts, [],
25 | exclude_binaries=True,
26 | name='laps-runner',
27 | contents_directory='.',
28 | debug=False,
29 | bootloader_ignore_signals=False,
30 | strip=False,
31 | upx=True,
32 | console=True,
33 | disable_windowed_traceback=False,
34 | argv_emulation=False,
35 | target_arch=None,
36 | codesign_identity=None,
37 | entitlements_file=None,
38 | )
39 | coll = COLLECT(exe, a.binaries, a.datas,
40 | strip=False,
41 | upx=True,
42 | upx_exclude=[],
43 | name='laps-runner',
44 | )
45 |
--------------------------------------------------------------------------------
/laps-runner/laps_runner/__init__.py:
--------------------------------------------------------------------------------
1 | __title__ = 'LAPS4LINUX'
2 | __author__ = 'Georg Sieber'
3 | __copyright__ = '© 2021-2025'
4 | __license__ = 'GPL-3.0'
5 | __version__ = '1.13.1'
6 | __website__ = 'https://github.com/schorschii/LAPS4LINUX'
7 |
8 | __all__ = [__author__, __license__, __version__]
9 |
--------------------------------------------------------------------------------
/laps-runner/laps_runner/filetime.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | from datetime import datetime
5 |
6 |
7 | # Microsoft Timestamp Conversion
8 |
9 | EPOCH_TIMESTAMP = 11644473600 # January 1, 1970 as MS file time
10 | HUNDREDS_OF_NANOSECONDS = 10000000
11 |
12 | def dt_to_filetime(dt):
13 | # dt.timestamp() returns UTC time as expected by the LDAP server
14 | return int((dt.timestamp() + EPOCH_TIMESTAMP) * HUNDREDS_OF_NANOSECONDS)
15 |
16 | def filetime_to_dt(ft):
17 | # ft is in UTC, fromtimestamp() converts to local time
18 | return datetime.fromtimestamp(int((ft / HUNDREDS_OF_NANOSECONDS) - EPOCH_TIMESTAMP))
19 |
--------------------------------------------------------------------------------
/laps-runner/laps_runner/laps_runner.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | from .__init__ import __title__, __version__, __website__, __author__, __copyright__
5 | from .filetime import dt_to_filetime, filetime_to_dt
6 |
7 | from pathlib import Path
8 | from os import path
9 | from crypt import crypt
10 | from datetime import datetime, timedelta
11 | from dns import resolver, rdatatype
12 | from shutil import which
13 | from pid import PidFile, PidFileAlreadyLockedError, PidFileAlreadyRunningError
14 | import time
15 | import struct
16 | import ssl
17 | import ldap3
18 | import subprocess
19 | import secrets
20 | import string
21 | import socket
22 | import getpass
23 | import argparse
24 | import json
25 | import sys, os
26 | import logging
27 | import logging.handlers
28 | import traceback
29 |
30 |
31 | class LapsRunner():
32 | server = None
33 | connection = None
34 | logger = None
35 |
36 | cfgPath = '/etc/laps-runner.json'
37 |
38 | cfgCredCacheFile = '/tmp/laps.temp'
39 | cfgClientKeytabFile = '/etc/krb5.keytab'
40 | cfgUseStartTls = True
41 | cfgServer = []
42 | cfgDomain = ''
43 | cfgLdapQuery = '(&(objectClass=computer)(cn=%1))'
44 |
45 | cfgHostname = None
46 | cfgUsername = 'root' # the user, whose password should be changed
47 | cfgDaysValid = 30 # how long the new password should be valid
48 | cfgLength = 15 # the generated password length
49 | cfgAlphabet = string.ascii_letters+string.digits+string.punctuation # allowed chars for the new password
50 |
51 | cfgUseNativeLapsAttributeSchema = True
52 | cfgSecurityDescriptor = None
53 | cfgHistorySize = 0 # disabled by default because encryption is disabled by default
54 | cfgLdapAttributePassword = 'msLAPS-Password'
55 | cfgLdapAttributePasswordHistory = 'msLAPS-EncryptedPasswordHistory'
56 | cfgLdapAttributePasswordExpiry = 'msLAPS-PasswordExpirationTime'
57 |
58 | cfgPamServices = [] # PAM_SERVICE filter
59 | cfgPamGracePeriod = 0 # timeout in seconds to wait before changing the password after logout
60 |
61 | cfgHooks = {}
62 |
63 | tmpDn = ''
64 | tmpPassword = None
65 | tmpExpiry = ''
66 | tmpExpiryDate = ''
67 |
68 | def __init__(self, *args, **kwargs):
69 | # init logger
70 | self.logger = logging.getLogger('LAPS4LINUX')
71 | self.logger.setLevel(logging.DEBUG)
72 | self.logger.addHandler(logging.handlers.SysLogHandler(address = '/dev/log'))
73 |
74 | # show note
75 | print(__title__ + ' Runner' +' v'+__version__)
76 | print('If you like LAPS4LINUX please do not forget to give the repository a star ('+__website__+').')
77 | print('')
78 |
79 | def getHostname(self):
80 | if(self.cfgHostname == None or self.cfgHostname.strip() == ''):
81 | return socket.gethostname().split('.', 1)[0].upper()
82 | else:
83 | return self.cfgHostname.strip().upper()
84 |
85 | def prepareEnvironment(self):
86 | # restore library search path for subprocess (modified by PyInstaller)
87 | # see https://pyinstaller.org/en/v6.9.0/common-issues-and-pitfalls.html#launching-external-programs-from-the-frozen-application
88 | sub_env = os.environ.copy()
89 | if('LD_LIBRARY_PATH_ORIG' in sub_env):
90 | sub_env['LD_LIBRARY_PATH'] = sub_env['LD_LIBRARY_PATH_ORIG']
91 | elif('LD_LIBRARY_PATH' in sub_env):
92 | del sub_env['LD_LIBRARY_PATH']
93 | return sub_env
94 |
95 | def initKerberos(self):
96 | # query new kerberos ticket
97 | cmd = ['kinit', '-k', '-c', self.cfgCredCacheFile, self.getHostname()+'$']
98 | res = subprocess.run(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, universal_newlines=True, env=self.prepareEnvironment())
99 | if res.returncode != 0: raise Exception(' '.join(cmd)+' returned non-zero exit code '+str(res.returncode))
100 |
101 | def connectToServer(self):
102 | # set environment variables for kerberos operations
103 | os.environ['KRB5CCNAME'] = self.cfgCredCacheFile
104 | os.environ['KRB5_CLIENT_KTNAME'] = self.cfgClientKeytabFile
105 |
106 | # set TLS options
107 | tlssettings = ldap3.Tls(
108 | validate=ssl.CERT_REQUIRED
109 | )
110 |
111 | # connect to server with kerberos ticket
112 | serverArray = []
113 | if(len(self.cfgServer) == 0):
114 | # query domain controllers by dns lookup
115 | searchDomain = '.'+self.cfgDomain if self.cfgDomain!='' else ''
116 | res = resolver.resolve(qname=f'_ldap._tcp'+searchDomain, rdtype=rdatatype.SRV, lifetime=10, search=True)
117 |
118 | for srv in res.rrset:
119 | if(self.cfgUseStartTls):
120 | # strip the trailing . from the dns resolver for certificate verification reasons.
121 | serverArray.append(ldap3.Server(host=str(srv.target).rstrip('.'), port=389, tls=tlssettings, get_info=ldap3.ALL))
122 | else:
123 | serverArray.append(ldap3.Server(host=str(srv.target).rstrip('.'), port=636, use_ssl=True, tls=tlssettings, get_info=ldap3.ALL))
124 | else:
125 | # use servers given in config file
126 | for server in self.cfgServer:
127 | serverArray.append(ldap3.Server(server['address'], port=server['port'], use_ssl=server['ssl'], get_info=ldap3.ALL))
128 | self.server = ldap3.ServerPool(serverArray, ldap3.ROUND_ROBIN, active=2, exhaust=True)
129 | if(self.cfgUseStartTls):
130 | self.connection = ldap3.Connection(self.server, version=3, authentication=ldap3.SASL, sasl_mechanism=ldap3.GSSAPI, auto_bind=ldap3.AUTO_BIND_TLS_BEFORE_BIND)
131 | self.connection.start_tls()
132 | else:
133 | self.connection = ldap3.Connection(self.server, version=3, authentication=ldap3.SASL, sasl_mechanism=ldap3.GSSAPI, auto_bind=True)
134 | print('Connected as: '+self.GetConnectionString())
135 |
136 | def searchComputer(self):
137 | if self.connection == None: raise Exception('No connection established')
138 |
139 | # check and escape input
140 | computerName = ldap3.utils.conv.escape_filter_chars(self.getHostname())
141 |
142 | # start query
143 | self.connection.search(
144 | search_base = self.createLdapBase(self.connection),
145 | search_filter = self.cfgLdapQuery.replace('%1', computerName),
146 | attributes = ldap3.ALL_ATTRIBUTES
147 | )
148 | for entry in self.connection.entries:
149 | # display result
150 | self.tmpDn = entry.entry_dn
151 | try:
152 | self.tmpPassword = entry[self.cfgLdapAttributePassword][0]
153 | except Exception:
154 | pass
155 | try:
156 | self.tmpExpiry = str(entry[self.cfgLdapAttributePasswordExpiry])
157 | except Exception:
158 | pass
159 | try:
160 | # date conversion will fail if there is no previous expiration time saved
161 | self.tmpExpiryDate = filetime_to_dt( int(str(entry[self.cfgLdapAttributePasswordExpiry])) )
162 | except Exception as e:
163 | print('Unable to parse date '+str(self.tmpExpiry)+' - assuming that no expiration date is set.')
164 | self.tmpExpiryDate = datetime.utcfromtimestamp(0)
165 | return True
166 |
167 | # no result found
168 | raise Exception('No Result For: '+computerName)
169 |
170 | def updatePassword(self):
171 | # check if usermod is in PATH
172 | if(which('usermod') is None): raise Exception('usermod is not in PATH')
173 |
174 | # generate new values
175 | newPassword = self.generatePassword()
176 | newPasswordHashed = crypt(newPassword)
177 | newExpirationDate = datetime.now() + timedelta(days=self.cfgDaysValid)
178 |
179 | # update in directory
180 | self.setPasswordAndExpiry(newPassword, newExpirationDate)
181 |
182 | # update password in local database
183 | cmd = ['usermod', '-p', newPasswordHashed, self.cfgUsername]
184 | res = subprocess.run(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, universal_newlines=True, env=self.prepareEnvironment())
185 | if res.returncode == 0:
186 | print('Password of user '+self.cfgUsername+' successfully changed in local database')
187 | self.logger.debug(__title__+': Changed password of user '+self.cfgUsername+' in local database')
188 | else:
189 | raise Exception(' '.join(cmd)+' returned non-zero exit code '+str(res.returncode))
190 |
191 | # execute hooks
192 | if(not isinstance(self.cfgHooks, dict)): return
193 | for hookName, hookArgs in self.cfgHooks.items():
194 | if(not isinstance(hookArgs, list)): continue
195 | replacements = {'$PASSWORD$':newPassword, '$USERNAME$':self.cfgUsername}
196 | cmd = [replacements.get(n, n) for n in hookArgs]
197 | res = subprocess.run(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, universal_newlines=True, env=self.prepareEnvironment())
198 | if res.returncode == 0:
199 | print('Hook '+hookName+' successfully executed')
200 | self.logger.debug(__title__+': Hook '+hookName+' successfully executed')
201 | else:
202 | print('Error: hook '+hookName+' returned non-zero exit code '+str(res.returncode))
203 | self.logger.debug(__title__+': '+'Error: hook '+hookName+' returned non-zero exit code '+str(res.returncode))
204 |
205 | def setPasswordAndExpiry(self, newPassword, newExpirationDate):
206 | # check if dn of target computer object is known
207 | if self.tmpDn.strip() == '': return
208 |
209 | # apply Native LAPS JSON format
210 | if(self.cfgUseNativeLapsAttributeSchema):
211 | print('Using Native LAPS JSON format')
212 | newPassword = json.dumps({
213 | 'p': newPassword,
214 | 'n': self.cfgUsername,
215 | 't': ('%0.2X' % dt_to_filetime(datetime.now())).lower()
216 | })
217 |
218 | # encrypt Native LAPS content
219 | if(self.cfgUseNativeLapsAttributeSchema and self.cfgSecurityDescriptor):
220 | print('Encrypting password to SID', self.cfgSecurityDescriptor)
221 | newPassword = self.encryptPassword(newPassword)
222 |
223 | # start query
224 | self.connection.modify(self.tmpDn, {
225 | self.cfgLdapAttributePasswordExpiry: [(ldap3.MODIFY_REPLACE, [str( dt_to_filetime(newExpirationDate) )])],
226 | self.cfgLdapAttributePassword: [(ldap3.MODIFY_REPLACE, [newPassword])],
227 | })
228 | if self.connection.result['result'] == 0:
229 | print('Password and expiration date changed successfully in LDAP directory (attribute '+self.cfgLdapAttributePassword+', new expiration '+str(newExpirationDate)+')')
230 | else:
231 | raise Exception('Could not update password in LDAP directory: '+str(self.connection.result))
232 |
233 | # update history
234 | if(self.tmpPassword and self.cfgHistorySize and self.cfgHistorySize > 0
235 | and self.cfgLdapAttributePasswordHistory and self.cfgLdapAttributePasswordHistory.strip() != ''):
236 | self.connection.modify(self.tmpDn, {
237 | self.cfgLdapAttributePasswordHistory: [(ldap3.MODIFY_ADD, self.tmpPassword)],
238 | })
239 | if self.connection.result['result'] != 0:
240 | raise Exception('Could not add previous password to history in LDAP directory: '+str(self.connection.result))
241 |
242 | # remove obsolete history entries
243 | self.connection.search(
244 | search_base = self.tmpDn,
245 | search_filter = '(objectClass=*)',
246 | attributes = [self.cfgLdapAttributePasswordHistory]
247 | )
248 | counter = 0
249 | deleteEntries = []
250 | for entry in self.connection.entries:
251 | for value in entry[self.cfgLdapAttributePasswordHistory]:
252 | counter += 1
253 | if counter > self.cfgHistorySize:
254 | deleteEntries.append(value)
255 | if len(deleteEntries) > 0: # when giving ldap3 an empty array, all entries will be removed!
256 | self.connection.modify(self.tmpDn, {
257 | self.cfgLdapAttributePasswordHistory: [(ldap3.MODIFY_DELETE, deleteEntries)],
258 | })
259 | if self.connection.result['result'] != 0:
260 | raise Exception('Could not remove old password from history in LDAP directory: '+str(self.connection.result))
261 | break
262 |
263 | def setExpiry(self, newExpirationDate):
264 | self.connection.modify(self.tmpDn, {
265 | self.cfgLdapAttributePasswordExpiry: [(ldap3.MODIFY_REPLACE, [str( dt_to_filetime(newExpirationDate) )])],
266 | })
267 |
268 | def encryptPassword(self, content):
269 | import dpapi_ng
270 | encrypted = None
271 | for server in self.server.servers:
272 | try: # one server could be unavailable, simply try the next one
273 | encrypted = dpapi_ng.ncrypt_protect_secret(
274 | content.encode('utf-16-le')+b"\x00\x00",
275 | self.cfgSecurityDescriptor,
276 | server = server.host,
277 | )
278 | break
279 | except Exception as e:
280 | print('Encryption attempt failed', e)
281 | if not encrypted: raise Exception('Unable to encrypt blob')
282 |
283 | # 0-4 - timestamp upper
284 | # 4-8 - timestamp lower
285 | # 8-12 - blob size, uint32
286 | # 12-16 - flags, currently always 0
287 | preMagic = (
288 | self.rotate_and_pack_msdatetime(dt_to_filetime(datetime.now()))
289 | + struct.pack('=3.1.0
2 | dnspython>=2.0.0
3 | dpapi-ng[kerberos]>=0.2.0
4 | gssapi; sys_platform != "win32" # needs libkrb5-dev
5 | winkerberos; sys_platform == "win32"
6 | ldap3>=2.9.1
7 | pid==3.0.4
8 |
--------------------------------------------------------------------------------
/laps-runner/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.command.clean import clean
2 | from distutils import log
3 | from setuptools import setup
4 | import os
5 |
6 | # Get the long description from the README file
7 | here = os.path.abspath(os.path.dirname(__file__))
8 | with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
9 | long_description = f.read()
10 |
11 | setup(
12 | name='laps4linux_runner',
13 | version=__import__('laps_runner').__version__,
14 | description='Rotate and store local administrator (LAPS) passwords in your AD/LDAP directory',
15 | long_description=long_description,
16 | long_description_content_type='text/markdown',
17 | install_requires=[i.strip() for i in open('requirements.txt').readlines()],
18 | license=__import__('laps_runner').__license__,
19 | author='Georg Sieber',
20 | keywords='laps password administrator ad ldap',
21 | url=__import__('laps_runner').__website__,
22 | classifiers=[
23 | 'Development Status :: 5 - Production/Stable',
24 | 'Intended Audience :: System Administrators',
25 | 'Operating System :: POSIX :: Linux',
26 | 'Operating System :: MacOS',
27 | 'Operating System :: Microsoft :: Windows',
28 | 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
29 | 'Programming Language :: Python',
30 | 'Programming Language :: Python :: 3',
31 | ],
32 | packages=['laps_runner'],
33 | entry_points={
34 | 'console_scripts': [
35 | 'laps-runner = laps_runner.laps_runner:main',
36 | ],
37 | },
38 | platforms=['all'],
39 | #install_requires=[],
40 | #test_suite='tests',
41 | )
42 |
--------------------------------------------------------------------------------