summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/general/plugins/modules/keyring.py
blob: 8329b727bd744bec7c64ced846036c2f48d35646 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2022, Alexander Hussey <ahussey@redhat.com>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Ansible Module - community.general.keyring
"""

from __future__ import absolute_import, division, print_function

__metaclass__ = type

DOCUMENTATION = r"""
---
module: keyring
version_added: 5.2.0
author:
  - Alexander Hussey (@ahussey-redhat)
short_description: Set or delete a passphrase using the Operating System's native keyring
description: >-
  This module uses the L(keyring Python library, https://pypi.org/project/keyring/)
  to set or delete passphrases for a given service and username from the OS' native keyring.
requirements:
  - keyring (Python library)
  - gnome-keyring (application - required for headless Gnome keyring access)
  - dbus-run-session (application - required for headless Gnome keyring access)
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  service:
    description: The name of the service.
    required: true
    type: str
  username:
    description: The user belonging to the service.
    required: true
    type: str
  user_password:
    description: The password to set.
    required: false
    type: str
    aliases:
      - password
  keyring_password:
    description: Password to unlock keyring.
    required: true
    type: str
  state:
    description: Whether the password should exist.
    required: false
    default: present
    type: str
    choices:
      - present
      - absent
"""

EXAMPLES = r"""
- name: Set a password for test/test1
  community.general.keyring:
    service: test
    username: test1
    user_password: "{{ user_password }}"
    keyring_password: "{{ keyring_password }}"

- name: Delete the password for test/test1
  community.general.keyring:
    service: test
    username: test1
    user_password: "{{ user_password }}"
    keyring_password: "{{ keyring_password }}"
    state: absent
"""

try:
    from shlex import quote
except ImportError:
    from pipes import quote
import traceback

from ansible.module_utils.basic import AnsibleModule, missing_required_lib

try:
    import keyring

    HAS_KEYRING = True
    KEYRING_IMP_ERR = None
except ImportError:
    HAS_KEYRING = False
    KEYRING_IMP_ERR = traceback.format_exc()


def del_passphrase(module):
    """
    Attempt to delete a passphrase in the keyring using the Python API and fallback to using a shell.
    """
    if module.check_mode:
        return None
    try:
        keyring.delete_password(module.params["service"], module.params["username"])
        return None
    except keyring.errors.KeyringLocked:
        delete_argument = (
            'echo "%s" | gnome-keyring-daemon --unlock\nkeyring del %s %s\n'
            % (
                quote(module.params["keyring_password"]),
                quote(module.params["service"]),
                quote(module.params["username"]),
            )
        )
        dummy, dummy, stderr = module.run_command(
            "dbus-run-session -- /bin/bash",
            use_unsafe_shell=True,
            data=delete_argument,
            encoding=None,
        )

        if not stderr.decode("UTF-8"):
            return None
        return stderr.decode("UTF-8")


def set_passphrase(module):
    """
    Attempt to set passphrase in the keyring using the Python API and fallback to using a shell.
    """
    if module.check_mode:
        return None
    try:
        keyring.set_password(
            module.params["service"],
            module.params["username"],
            module.params["user_password"],
        )
        return None
    except keyring.errors.KeyringLocked:
        set_argument = (
            'echo "%s" | gnome-keyring-daemon --unlock\nkeyring set %s %s\n%s\n'
            % (
                quote(module.params["keyring_password"]),
                quote(module.params["service"]),
                quote(module.params["username"]),
                quote(module.params["user_password"]),
            )
        )
        dummy, dummy, stderr = module.run_command(
            "dbus-run-session -- /bin/bash",
            use_unsafe_shell=True,
            data=set_argument,
            encoding=None,
        )
        if not stderr.decode("UTF-8"):
            return None
        return stderr.decode("UTF-8")


def get_passphrase(module):
    """
    Attempt to retrieve passphrase from keyring using the Python API and fallback to using a shell.
    """
    try:
        passphrase = keyring.get_password(
            module.params["service"], module.params["username"]
        )
        return passphrase
    except keyring.errors.KeyringLocked:
        pass
    except keyring.errors.InitError:
        pass
    except AttributeError:
        pass
    get_argument = 'echo "%s" | gnome-keyring-daemon --unlock\nkeyring get %s %s\n' % (
        quote(module.params["keyring_password"]),
        quote(module.params["service"]),
        quote(module.params["username"]),
    )
    dummy, stdout, dummy = module.run_command(
        "dbus-run-session -- /bin/bash",
        use_unsafe_shell=True,
        data=get_argument,
        encoding=None,
    )
    try:
        return stdout.decode("UTF-8").splitlines()[1]  # Only return the line containing the password
    except IndexError:
        return None


def run_module():
    """
    Attempts to retrieve a passphrase from a keyring.
    """
    result = dict(
        changed=False,
        msg="",
    )

    module_args = dict(
        service=dict(type="str", required=True),
        username=dict(type="str", required=True),
        keyring_password=dict(type="str", required=True, no_log=True),
        user_password=dict(
            type="str", required=False, no_log=True, aliases=["password"]
        ),
        state=dict(
            type="str", required=False, default="present", choices=["absent", "present"]
        ),
    )

    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    if not HAS_KEYRING:
        module.fail_json(msg=missing_required_lib("keyring"), exception=KEYRING_IMP_ERR)

    passphrase = get_passphrase(module)
    if module.params["state"] == "present":
        if passphrase is not None:
            if passphrase == module.params["user_password"]:
                result["msg"] = "Passphrase already set for %s@%s" % (
                    module.params["service"],
                    module.params["username"],
                )
            if passphrase != module.params["user_password"]:
                set_result = set_passphrase(module)
                if set_result is None:
                    result["changed"] = True
                    result["msg"] = "Passphrase has been updated for %s@%s" % (
                        module.params["service"],
                        module.params["username"],
                    )
                if set_result is not None:
                    module.fail_json(msg=set_result)
        if passphrase is None:
            set_result = set_passphrase(module)
            if set_result is None:
                result["changed"] = True
                result["msg"] = "Passphrase has been updated for %s@%s" % (
                    module.params["service"],
                    module.params["username"],
                )
            if set_result is not None:
                module.fail_json(msg=set_result)

    if module.params["state"] == "absent":
        if not passphrase:
            result["result"] = "Passphrase already absent for %s@%s" % (
                module.params["service"],
                module.params["username"],
            )
        if passphrase:
            del_result = del_passphrase(module)
            if del_result is None:
                result["changed"] = True
                result["msg"] = "Passphrase has been removed for %s@%s" % (
                    module.params["service"],
                    module.params["username"],
                )
            if del_result is not None:
                module.fail_json(msg=del_result)

    module.exit_json(**result)


def main():
    """
    main module loop
    """
    run_module()


if __name__ == "__main__":
    main()