summaryrefslogtreecommitdiffstats
path: root/src/software/test/test_software_identity_file_check.py
blob: 49cd97d3908bdf2baeacd9ec7f359072e1fcfa0b (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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/env python
#
# Copyright (C) 2012-2013 Red Hat, Inc.  All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# Authors: Michal Minar <miminar@redhat.com>
#
"""
Unit tests for LMI_SoftwareIdentity provider.
"""

import os
import pywbem
import re
import socket
import subprocess
import unittest

import base
import rpmcache

RE_CHECKSUM = re.compile(r'^([0-9a-fA-F]+)\s+.*')

class TestSoftwareIdentityFileCheck(
        base.SoftwareBaseTestCase): #pylint: disable=R0904
    """
    Basic cim operations test.
    """

    CLASS_NAME = "LMI_SoftwareIdentityFileCheck"
    KEYS = ("CheckID", "Name", "SoftwareElementID", "SoftwareElementState")

    # maps algorithm id to the shell command
    HASH_COMMAND = {
            1  : "md5sum",
            2  : "sha1sum",
            8  : "sha256sum",
            9  : "sha384sum",
            10 : "sha512sum",
            11 : "sha224sum"
    }

    # maps algorithm id to the length of digest string
    HASH_DIGEST_LENGTH = {
            1  : 32,    #MD5
            2  : 40,    #SHA1
            8  : 64,    #SHA256
            9  : 96,    #SHA384
            10 : 128,   #SHA512
            11 : 56     #SHA224
    }

    @classmethod
    def needs_pkgdb_files(cls):
        return True

    def make_checksum_str(self, csumnum, filename):
        """
        @return checksum of installed file
        """
        return RE_CHECKSUM.match(subprocess.check_output([
            self.HASH_COMMAND[csumnum], filename])).group(1).lower()

    def make_op(self, pkg, file_name, newer=True):
        """
        :rtype: (``pywbem.CIMInstanceName``) object path of
            SoftwareIdentityFileCheck
        """
        objpath = self.objpath.copy()
        objpath["CheckID"] = 'LMI:LMI_SoftwareIdentityFileCheck'
        objpath["Name"] = file_name
        objpath["SoftwareElementID"] = pkg.get_nevra(
                newer=newer, with_epoch="ALWAYS")
        objpath["SoftwareElementState"] = pywbem.Uint16(2)      #Executable
        objpath["TargetOperatingSystem"] = pywbem.Uint16(36)    #LINUX
        objpath["Version"] = getattr(pkg, 'up_evra' if newer else 'evra')
        return objpath

    def do_check_symlink(self, pkg, filepath, inst, safe=False):
        """
        Assert some details about symlink.
        :param safe: (``bool``) If True, no modification is done to file.
        """
        target = os.readlink(filepath)
        stats = os.lstat(filepath)

        self.assertEqual(pywbem.Uint16(3), inst["FileType"],
                "Unexpected file type of symlink for %s:%s"%(
                    pkg.name, filepath))
        self.assertEqual(stats.st_uid, inst["UserID"],
                "Unexpected uid of symlink for %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_gid, inst["GroupID"],
                "Unexpected gid of symlink for %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_mode, inst["FileMode"],
                "Unexpected mode of symlink for %s:%s" %(pkg.name, filepath))
        self.assertEqual(stats.st_size, inst["FileSize"],
                "Unexpected size of symlink for %s:%s"%(pkg.name, filepath))
        self.assertEqual(target, inst["LinkTarget"],
                "Unexpected size of symlink for %s:%s"%(pkg.name, filepath))
        self.assertEqual(int(stats.st_mtime), inst["LastModificationTime"],
                "Unexpected mtime of symlink for %s:%s"%(pkg.name, filepath))
        self.assertIsNone(inst["Checksum"],
                "Checksum should be None for symlink %s:%s"%(
                    pkg.name, filepath))
        self.assertIsNone(inst["FileChecksum"],
                "FileChecksum should be None for symlink %s:%s"%(
                    pkg.name, filepath))
        self.assertIsNone(inst["MD5Checksum"],
                "MD5Checksum should be None for symlink %s:%s"%(
                    pkg.name, filepath))

        if safe:
            return

        # modify owner
        prev_user = inst["UserID"]
        os.lchown(filepath, stats.st_uid + 1, -1)
        inst = self.conn.GetInstance(InstanceName=inst.path)
        self.assertEqual(inst["UserIDOriginal"] + 1, inst["UserID"],
            "Unexpected uid of modified symlink for %s:%s"%(
            pkg.name, filepath))
        self.assertEqual(prev_user + 1, inst["UserID"],
            "Unexpected uid of modified symlink for %s:%s"%(
            pkg.name, filepath))
        self.assertEqual(stats.st_gid, inst["GroupID"],
            "Unexpected gid of modified symlink for %s:%s"%(
            pkg.name, filepath))
        self.assertEqual([
                pywbem.Uint16(7) #UserID
            ], inst["FailedFlags"])

        # modify link_target
        os.remove(filepath)
        lt_modif = "wrong" + "*"*len(inst["LinkTargetOriginal"])
        os.symlink(lt_modif, filepath)
        os.lchown(filepath, inst["UserIDOriginal"], inst["GroupIDOriginal"])

        inst = self.conn.GetInstance(InstanceName=inst.path)
        self.assertEqual(set([
                pywbem.Uint16(1), #FileSize
                pywbem.Uint16(6), #LinkTarget
            ]), set(inst["FailedFlags"]))
        self.assertGreater(len(inst["LinkTarget"]),
                len(inst["LinkTargetOriginal"]))

        self.assertTrue(inst["FileExists"],
            "File %s:%s should exist"%(pkg.name, filepath))
        self.assertEqual(inst["FileTypeOriginal"], inst["FileType"],
            "File type should match for symlink %s:%s"%(pkg.name, filepath))
        self.assertNotEqual(inst["FileSizeOriginal"], inst["FileSize"],
            "File size should not match for symlink %s:%s"%(
                pkg.name, filepath))
        self.assertEqual(inst["FileModeOriginal"], inst["FileMode"],
            "File mode should match for symlink %s:%s"%(pkg.name, filepath))
        self.assertEqual(lt_modif, inst["LinkTarget"],
            "Link target should match modified path %s:%s"%(
                pkg.name, filepath))
        self.assertNotEqual(inst["LinkTargetOriginal"], inst["ListTarget"],
            "Link target should not match for symlink %s:%s"%(
                pkg.name, filepath))
        self.assertEqual(inst["UserIDOriginal"], inst["UserID"],
            "File uid should match for symlink %s:%s"%(pkg.name, filepath))
        self.assertEqual(inst["GroupIDOriginal"], inst["GroupID"],
            "File gid should match for symlink %s:%s"%(pkg.name, filepath))

    def do_check_directory(self, pkg, filepath, inst):
        """
        Assert some details about directory.
        """
        stats = os.lstat(filepath)

        self.assertEqual(pywbem.Uint16(2), inst["FileType"],
                "Unexpected type for directory %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_uid, inst["UserID"],
                "Unexpected uid for directory %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_gid, inst["GroupID"],
                "Unexpected gid for directory %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_mode, inst["FileMode"],
                "Unexpected mode for directory %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_size, inst["FileSize"],
                "Unexpected size for directory %s:%s"%(pkg.name, filepath))
        self.assertIs(inst["LinkTarget"], None)
        self.assertIsNone(inst["FileChecksum"],
                "Unexpected checksum for directory %s:%s"%(pkg.name, filepath))
        self.assertEqual(int(stats.st_mtime), inst["LastModificationTime"],
                "Unexpected mtime for directory %s:%s"%(pkg.name, filepath))
        self.assertEqual([], inst["FailedFlags"])

    def do_check_file(self, pkg, filepath, inst, safe=False):
        """
        Assert some details about regular file.
        :param safe: (``bool``) If True, no modification is done to file.
        """
        stats = os.lstat(filepath)

        self.assertEqual(pywbem.Uint16(1), inst["FileType"],
            "Unexpected file type for %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_uid, inst["UserID"],
            "Unexpected file uid for %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_gid, inst["GroupID"],
            "Unexpected gid for regular file %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_mode, inst["FileMode"],
            "Unexpected mode for regular file %s:%s"%(pkg.name, filepath))
        self.assertEqual(stats.st_size, inst["FileSize"],
            "Unexpected size for regular file %s:%s"%(pkg.name, filepath))
        self.assertIs(inst["LinkTarget"], None)
        csum = self.make_checksum_str(inst['ChecksumType'], filepath)
        self.assertEqual(csum, inst["FileChecksum"].lower(),
            "Unexpected checksum for regular file %s:%s"%(pkg.name, filepath))
        self.assertEqual(inst["LastModificationTime"],
                inst["LastModificationTimeOriginal"],
                "Unexpected mtime for regular file %s:%s"%(pkg.name, filepath))
        self.assertEqual(int(stats.st_mtime), inst["LastModificationTime"],
                "Unexpected mtime for regular file %s:%s"%(pkg.name, filepath))

        if safe:
            return

        # make it longer
        with open(filepath, "a+") as fobj:
            fobj.write("data\n")
        inst = self.conn.GetInstance(InstanceName=inst.path)
        self.assertEqual(set([
                pywbem.Uint16(1),   #FileSize
                pywbem.Uint16(3),   #Checksum
                pywbem.Uint16(9),   #LastModificationTime
                ]), set(inst["FailedFlags"]))

        self.assertGreater(inst["FileSize"], inst["FileSizeOriginal"],
                "File size should be greater, then expected for regular file"
                " %s:%s"%(pkg.name, filepath))
        self.assertGreater(inst["LastModificationTime"],
                inst["LastModificationTimeOriginal"],
                "Unexpected mtime for regular file %s:%s"%(pkg.name, filepath))

        self.assertTrue(inst["FileExists"],
            "Regular file should exist %s:%s"%(pkg.name, filepath))

        # change file type
        os.remove(filepath)
        os.symlink(filepath, filepath)
        os.lchown(filepath, inst["UserIDOriginal"],
                inst["GroupIDOriginal"])
        inst = self.conn.GetInstance(InstanceName=inst.path)
        self.assertNotEqual(inst["LinkTargetOriginal"], inst["LinkTarget"],
                "Link target should not match for %s:%s"%(pkg.name, filepath))
        self.assertNotEqual(inst["FileSizeOriginal"], inst["FileSize"],
                "File size should not match for %s:%s"%(pkg.name, filepath))
        self.assertGreater(inst["LastModificationTime"],
                inst["LastModificationTimeOriginal"],
                "File mtime should be greater than expected for %s:%s"%(
                    pkg.name, filepath))
        self.assertNotEqual(inst["FileTypeOriginal"], inst["FileType"],
                "File type should not match for %s:%s"%(pkg.name, filepath))
        self.assertEqual(pywbem.Uint16(3), inst["FileType"],
                "File type should match for %s:%s"%(pkg.name, filepath))
        self.assertIn(pywbem.Uint16(2),     #FileMode
                inst["FailedFlags"])

        # remove it
        os.remove(filepath)
        inst = self.conn.GetInstance(InstanceName=inst.path)
        self.assertEqual(inst["LinkTargetOriginal"], inst["LinkTarget"],
                "Link target does not match for regular file %s:%s"%(
                    pkg.name, filepath))
        self.assertNotEqual(inst["FileSizeOriginal"], inst["FileSize"],
                "File size should not match for regular file %s:%s"%(
                    pkg.name, filepath))
        self.assertIsNone(inst["LastModificationTime"])
        self.assertIsNone(inst["FileType"])
        self.assertIsNone(inst["FileChecksum"])
        self.assertIsNone(inst["FileMode"])
        self.assertIsNone(inst["UserID"])
        self.assertIsNone(inst["GroupID"])
        self.assertEqual([
                pywbem.Uint16(0), #exists
            ], inst["FileExists"])

    def check_filepath(self, pkg, filepath, safe=False):
        """
        Make a check of particular file of package.
        All files are expected to have no flaw.

        :param safe: (``bool``) says, whether modifications to file can be done
        """
        objpath = self.make_op(pkg, filepath)
        inst = self.conn.GetInstance(InstanceName=objpath)
        self.assertIsInstance(inst, pywbem.CIMInstance)
        self.assertEqual(objpath, inst.path,
            msg="Object paths of instance must match for %s:%s"%(
            pkg.name, filepath))
        for key in self.KEYS:
            if key.lower() == "targetoperatingsystem":
                self.assertIsInstance(objpath[key], (int, long))
            else:
                self.assertEqual(objpath[key], inst[key],
                    "OP key %s values should match for %s:%s"%(
                    key, pkg.name, filepath))

        self.assertTrue(inst["FileExists"],
            "File %s:%s must exist"%(pkg.name, filepath))
        self.assertEqual(0, len(inst["FailedFlags"]),
            "FailedFlags must be empty")

        for prop in ( "FileType", "UserID", "GroupID"
                    , "FileMode", "FileSize", "LinkTarget"
                    , "FileChecksum", "FileModeFlags"):
            if (  (  (  os.path.islink(filepath)
                     or (not os.path.isfile(filepath)))
                  and prop == "FileSize")
               or (os.path.islink(filepath) and prop == "FileMode")):
                continue
            self.assertEqual(inst[prop+"Original"], inst[prop],
                "%s should match for %s:%s"%(prop, pkg.name, filepath))
        if os.path.islink(filepath):
            self.do_check_symlink(pkg, filepath, inst, safe=safe)
        elif os.path.isdir(filepath):
            self.do_check_directory(pkg, filepath, inst)
        elif os.path.isfile(filepath):
            self.do_check_file(pkg, filepath, inst, safe=safe)

    def test_get_instance_safe(self):
        """
        Tests GetInstance call.
        """
        for pkg in self.safe_pkgs:
            files = self.pkgdb_files[pkg.name]
            for filepath in files:
                self.check_filepath(pkg, filepath, safe=True)

    def test_enum_instance_names(self):
        """
        Tests EnumInstanceNames - which should not be supported.
        """
        self.assertRaisesCIM(pywbem.CIM_ERR_NOT_SUPPORTED,
                self.conn.EnumerateInstanceNames, ClassName=self.CLASS_NAME)

    def test_invoke_method_safe(self):
        """
        Test Invoke method in a safe manner.
        """
        for pkg in self.safe_pkgs:
            files = self.pkgdb_files[pkg.name]
            for filepath in files:
                objpath = self.make_op(pkg, filepath)

                (rval, _) = self.conn.InvokeMethod(
                        MethodName="Invoke",
                        ObjectName=objpath)
                self.assertEqual(pywbem.Uint32(0),   #Satisfied
                        rval,
                        msg="Invoke method should be successful for %s:%s"%(
                            pkg.name, filepath))

                (rval, _) = self.conn.InvokeMethod(
                        MethodName="InvokeOnSystem",
                        ObjectName=objpath,
                        TargetSystem=pywbem.CIMInstanceName(
                            namespace="root/cimv2",
                            classname="Linux_ComputerSystem",
                            keybindings=pywbem.NocaseDict({
                                "CreationClassName" : "Linux_ComputerSystem",
                                "Name" : socket.getfqdn()})))

                self.assertEqual(pywbem.Uint32(0),  #Satisfied
                        rval, msg="InvokeOnSystem method should be successful"
                            " for %s:%s"%(pkg.name, filepath))

                self.assertRaisesCIM(pywbem.CIM_ERR_NOT_FOUND,
                        self.conn.InvokeMethod,
                        MethodName="InvokeOnSystem",
                        ObjectName=objpath,
                        TargetSystem=pywbem.CIMInstanceName(
                            namespace="root/cimv2",
                            classname="Linux_ComputerSystem",
                            keybindings=pywbem.NocaseDict({
                                "CreationClassName" : "Bad class name",
                                "Name" : "some random name"})))

    @base.mark_dangerous
    def test_invoke_method(self):
        """
        Tests Invoke method invocation.
        """
        for pkg in self.dangerous_pkgs:
            if not rpmcache.is_pkg_installed(pkg.name):
                rpmcache.install_pkg(pkg.name)
            for filepath in self.pkgdb_files[pkg.name]:
                objpath = self.make_op(pkg, filepath)

                (rval, _) = self.conn.InvokeMethod(
                        MethodName="Invoke",
                        ObjectName=objpath)
                self.assertEqual(pywbem.Uint32(0)   #Satisfied
                        , rval,
                    msg="Invoke method should be successful for %s:%s"%(
                    pkg.name, filepath))

                # modify file
                if os.path.isfile(filepath):
                    os.remove(filepath)
                else:
                    os.lchown(filepath, os.stat(filepath).st_uid + 1, -1)
                (rval, _) = self.conn.InvokeMethod(
                        MethodName="Invoke",
                        ObjectName=objpath)
                self.assertEqual(
                        pywbem.Uint32(2), #Not Satisfied
                        rval,
                    "Invoke method should not pass for modified file %s:%s"%(
                    pkg.name, filepath))

def suite():
    """For unittest loaders."""
    return unittest.TestLoader().loadTestsFromTestCase(
            TestSoftwareIdentityFileCheck)

if __name__ == '__main__':
    unittest.main()