summaryrefslogtreecommitdiffstats
path: root/meta-security/classes/xattr-images.bbclass
blob: 565a3fb6e385a4f68d579d068e4961c8815d1947 (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
# Both Smack and IMA/EVM rely on xattrs. Inheriting this class ensures
# that these xattrs get preserved in tar and jffs2 images.
#
# It also fixes the rootfs so that the content of directories with
# SMACK::TRANSMUTE is correctly labelled. This is because pseudo does
# not know the special semantic of SMACK::TRANSMUTE and omits the
# updating of the Smack label when creating entries inside such a directory,
# for example /etc (see base-files_%.bbappend). Without the fixup,
# files already installed during the image creation would have different (and
# wrong) Smack labels.

# xattr support is expected to be compiled into mtd-utils. We just need to
# use it.
EXTRA_IMAGECMD_jffs2_append = " --with-xattr"

# By default, OE-core uses tar from the host, which may or may not have the
# --xattrs parameter which was introduced in 1.27. For image building we
# use a recent enough tar instead.
#
# The GNU documentation does not specify whether --xattrs-include is necessary.
# In practice, it turned out to be not needed when creating archives and
# required when extracting, but it seems prudent to use it in both cases.
IMAGE_DEPENDS_tar_append = " tar-replacement-native"
EXTRANATIVEPATH += "tar-native"
IMAGE_CMD_TAR = "tar --xattrs --xattrs-include=*"

xattr_images_fix_transmute[dirs] = "${IMAGE_ROOTFS}"
python xattr_images_fix_transmute () {
    # The recursive updating of the Smack label ensures that each entry
    # has the label set for its parent directories if one of those was
    # marked as transmuting.
    #
    # In addition, "_" is set explicitly on everything that would not
    # have a label otherwise. This is a workaround for tools like swupd
    # which transfers files from a rootfs onto a target device where Smack
    # is active: on the target, each file gets assigned a label, typically
    # the one from the process which creates it. swupd (or rather, the tools
    # it is currently built on) knows how to set security.SMACK64="_" when
    # it is set on the original files, but it does not know that it needs
    # to remove that xattr when not set.
    import os
    import errno

    if getattr(os, 'getxattr', None):
        # Python 3: os has xattr support.
        def lgetxattr(f, attr):
            try:
                value = os.getxattr(f, attr, follow_symlinks=False)
                return value.decode('utf8')
            except OSError as ex:
                if ex.errno == errno.ENODATA:
                    return None

        def lsetxattr(f, attr, value):
            os.setxattr(f, attr.encode('utf8'), value.encode('utf8'), follow_symlinks=False)
    else:
        # Python 2: xattr support only in xattr module.
        #
        # Cannot use the 'xattr' module, it is not part of a standard Python
        # installation. Instead re-implement using ctypes. Only has to be good
        # enough for xattrs that are strings. Always operates on the symlinks themselves,
        # not what they point to.
        import ctypes

        # We cannot look up the xattr functions inside libc. That bypasses
        # pseudo, which overrides these functions via LD_PRELOAD. Instead we have to
        # find the function address and then create a ctypes function from it.
        libdl = ctypes.CDLL("libdl.so.2")
        _dlsym = libdl.dlsym
        _dlsym.restype = ctypes.c_void_p
        RTLD_DEFAULT = ctypes.c_void_p(0)
        _lgetxattr = ctypes.CFUNCTYPE(ctypes.c_ssize_t, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_size_t,
                    use_errno=True)(_dlsym(RTLD_DEFAULT, 'lgetxattr'))
        _lsetxattr = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int,
                    use_errno=True)(_dlsym(RTLD_DEFAULT, 'lsetxattr'))

        def lgetxattr(f, attr):
            len = 32
            while True:
                buffer = ctypes.create_string_buffer('\000' * len)
                res = _lgetxattr(f, attr, buffer, ctypes.c_size_t(len))
                if res >= 0:
                    return buffer.value
                else:
                    error = ctypes.get_errno()
                    if ctypes.get_errno() == errno.ERANGE:
                        len *= 2
                    elif error == errno.ENODATA:
                        return None
                    else:
                        raise IOError(error, 'lgetxattr(%s, %s): %d = %s = %s' %
                                             (f, attr, error, errno.errorcode[error], os.strerror(error)))

        def lsetxattr(f, attr, value):
            res = _lsetxattr(f, attr, value, ctypes.c_size_t(len(value)), ctypes.c_int(0))
            if res != 0:
                error = ctypes.get_errno()
                raise IOError(error, 'lsetxattr(%s, %s, %s): %d = %s = %s' %
                                     (f, attr, value, error, errno.errorcode[error], os.strerror(error)))

    def visit(path, deflabel, deftransmute):
        isrealdir = os.path.isdir(path) and not os.path.islink(path)
        curlabel = lgetxattr(path, 'security.SMACK64')
        transmute = lgetxattr(path, 'security.SMACK64TRANSMUTE') == 'TRUE'

        if not curlabel:
            # Since swupd doesn't remove the label from an updated file assigned by
            # the target device's kernel upon unpacking the file from an update,
            # we have to set the floor label explicitly even though it is the default label
            # and thus adding it would create additional overhead. Otherwise this
            # would result in hash mismatches reported by `swupd verify`.
            lsetxattr(path, 'security.SMACK64', deflabel)
            if not transmute and deftransmute and isrealdir:
                lsetxattr(path, 'security.SMACK64TRANSMUTE', 'TRUE')

        # Identify transmuting directories and change the default Smack
        # label inside them. In addition, directories themselves must become
        # transmuting.
        if isrealdir:
            if transmute:
                deflabel = lgetxattr(path, 'security.SMACK64')
                deftransmute = True
                if deflabel is None:
                    raise RuntimeError('%s: transmuting directory without Smack label' % path)
            elif curlabel:
                # Directory with explicit label set and not transmuting => do not
                # change the content unless we run into another transmuting directory.
               deflabel = '_'
               deftransmute = False

            for entry in os.listdir(path):
                visit(os.path.join(path, entry), deflabel, deftransmute)

    visit('.', '_', False)
}
# Same logic as in ima-evm-rootfs.bbclass: try to run as late as possible.
IMAGE_PREPROCESS_COMMAND_append_with-lsm-smack = " xattr_images_fix_transmute ; "
pan> *********************************************************************************/ static int make_subscription_unsubscription(struct afb_req request, const std::string& sig_name, std::map<std::string, struct afb_event>& s, bool subscribe) { /* Make the subscription or unsubscription to the event */ if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[sig_name.c_str()])) < 0) { ERROR(binder_interface, "Operation goes wrong for signal: %s", sig_name); return 0; } return 1; } static int create_event_handle(const std::string& sig_name, std::map<std::string, struct afb_event>& s) { s[sig_name] = afb_daemon_make_event(binder_interface->daemon, sig_name.c_str()); if (!afb_event_is_valid(s[sig_name])) { ERROR(binder_interface, "Can't create an event, something goes wrong."); return 0; } return 1; } static int subscribe_unsubscribe_signal(struct afb_req request, bool subscribe, const std::string& sig) { int ret; std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex()); std::map<std::string, struct afb_event>& s = get_subscribed_signals(); if (s.find(sig) != s.end() && !afb_event_is_valid(s[sig])) { if(!subscribe) { NOTICE(binder_interface, "Event isn't valid, it can't be unsubscribed."); ret = -1; } else { /* Event it isn't valid annymore, recreate it */ ret = create_event_handle(sig, s); } } else { /* Event doesn't exist , so let's create it */ struct afb_event empty_event = {nullptr, nullptr}; subscribed_signals[sig] = empty_event; ret = create_event_handle(sig, s); } /* Check whether or not the event handler has been correctly created and * make the subscription/unsubscription operation is so. */ if (ret <= 0) return ret; return make_subscription_unsubscription(request, sig, s, subscribe); } /** * @fn static int subscribe_unsubscribe_signals(struct afb_req request, bool subscribe, const std::vector<can_signal_t>& signals) * @brief subscribe to all signals in the vector signals * * @param[in] afb_req request : contain original request use to subscribe or unsubscribe * @param[in] subscribe boolean value used to chose between a subscription operation or an unsubscription * @param[in] can_signal_t vector with can_signal_t to subscribe * * @return Number of correctly subscribed signal */ static int subscribe_unsubscribe_signals(struct afb_req request, bool subscribe, const std::vector<std::string>& signals) { int rets = 0; sd_event_source *source; //TODO: Implement way to dynamically call the right function no matter // how much signals types we have. /// const std::string& can_prefix = configuration_t::instance().get_can_signals().front().get_prefix(); const std::string& obd2_prefix = configuration_t::instance().get_obd2_signals().front().get_prefix(); for(const std::string& sig : signals) { int ret; if (sig.find_first_of(obd2_prefix.c_str(), 0, obd2_prefix.size())) { std::vector<obd2_signal_t*> found; configuration_t::instance().find_obd2_signals(build_DynamicField(sig), found); int frequency = found.front()->get_frequency(); DiagnosticRequest* diag_req = new DiagnosticRequest(found.front()->build_diagnostic_request()); configuration_t::instance().get_diagnostic_manager().add_recurring_request( diag_req, sig.c_str(), false, obd2_signal_t::decode_obd2_response, nullptr, (float)frequency); //TODO: Adding callback requesting ignition status: diag_req, sig.c_str(), false, obd2_signal_t::decode_obd2_response, obd2_signal_t::check_ignition_status, frequency); sd_event_add_time(afb_daemon_get_event_loop(binder_interface->daemon), &source, CLOCK_MONOTONIC, frequency, 0, configuration_t::instance().get_diagnostic_manager().send_request, diag_req); } ret = subscribe_unsubscribe_signal(request, subscribe, sig); if(ret <= 0) return ret; rets++; DEBUG(binder_interface, "Signal: %s subscribed", sig.c_str()); } return rets; } static int subscribe_unsubscribe_name(struct afb_req request, bool subscribe, const char *name) { std::vector<std::string> signals; int ret = 0; openxc_DynamicField search_key = build_DynamicField(std::string(name)); signals = find_signals(search_key); if (signals.empty()) ret = 0; ret = subscribe_unsubscribe_signals(request, subscribe, signals); NOTICE(binder_interface, "Subscribed correctly to %d/%d signal(s).", ret, (int)signals.size()); return ret; } static void subscribe_unsubscribe(struct afb_req request, bool subscribe) { int ok, i, n; struct json_object *args, *a, *x; /* makes the subscription/unsubscription */ args = afb_req_json(request); if (args == NULL || !json_object_object_get_ex(args, "event", &a)) { ok = subscribe_unsubscribe_name(request, subscribe, "*"); } else if (json_object_get_type(a) != json_type_array) { ok = subscribe_unsubscribe_name(request, subscribe, json_object_get_string(a)); } else { n = json_object_array_length(a); ok = 0; for (i = 0 ; i < n ; i++) { x = json_object_array_get_idx(a, i); if (subscribe_unsubscribe_name(request, subscribe, json_object_get_string(x))) ok++; } ok = (ok == n); } /* send the report */ if (ok) afb_req_success(request, NULL, NULL); else afb_req_fail(request, "error", NULL); } extern "C" { static void subscribe(struct afb_req request) { subscribe_unsubscribe(request, true); } static void unsubscribe(struct afb_req request) { subscribe_unsubscribe(request, false); } static const struct afb_verb_desc_v1 verbs[]= { { .name= "subscribe", .session= AFB_SESSION_NONE, .callback= subscribe, .info= "subscribe to notification of CAN bus messages." }, { .name= "unsubscribe", .session= AFB_SESSION_NONE, .callback= unsubscribe, .info= "unsubscribe a previous subscription." } }; static const struct afb_binding binding_desc { AFB_BINDING_VERSION_1, { "Low level CAN bus service", "low-can", verbs } }; const struct afb_binding *afbBindingV1Register (const struct afb_binding_interface *itf) { binder_interface = itf; return &binding_desc; } /** * @brief Initialize the binding. * * @param[in] service Structure which represent the Application Framework Binder. * * @return Exit code, zero if success. */ int afbBindingV1ServiceInit(struct afb_service service) { can_bus_t& can_bus_manager = configuration_t::instance().get_can_bus_manager(); /// Initialize CAN socket if(can_bus_manager.init_can_dev() == 0) { can_bus_manager.start_threads(); return 0; } /// Initialize Diagnostic manager that will handle obd2 requests diagnostic_manager_t& diag_manager = configuration_t::instance().get_diagnostic_manager(); diag_manager.initialize(can_bus_manager.get_can_devices().front()); ERROR(binder_interface, "There was something wrong with CAN device Initialization. Check your config file maybe"); return 1; } };