summaryrefslogtreecommitdiff
path: root/src/security/security_apparmor.c
blob: dd8f7d3808f3400aeec0759e024d9af27a39dc18 (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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
/*
 * AppArmor security driver for libvirt
 *
 * Copyright (C) 2011-2014 Red Hat, Inc.
 * Copyright (C) 2009-2010 Canonical Ltd.
 *
 * 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, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/apparmor.h>
#include <unistd.h>
#include <wait.h>

#include "internal.h"

#include "security_apparmor.h"
#include "viralloc.h"
#include "virerror.h"
#include "datatypes.h"
#include "viruuid.h"
#include "virpci.h"
#include "virusb.h"
#include "virscsivhost.h"
#include "virfile.h"
#include "configmake.h"
#include "vircommand.h"
#include "virlog.h"
#include "virstring.h"
#include "virscsi.h"
#include "virmdev.h"

#define VIR_FROM_THIS VIR_FROM_SECURITY

VIR_LOG_INIT("security.security_apparmor");

#define SECURITY_APPARMOR_VOID_DOI      "0"
#define SECURITY_APPARMOR_NAME          "apparmor"
#define VIRT_AA_HELPER LIBEXECDIR "/virt-aa-helper"

/* Data structure to pass to *FileIterate so we have everything we need */
struct SDPDOP {
    virSecurityManagerPtr mgr;
    virDomainDefPtr def;
};

/*
 * profile_status returns '-2' on error, '-1' if not loaded, '0' if loaded
 *
 * If check_enforcing is set to '1', then returns '-2' on error, '-1' if
 * not loaded, '0' if loaded in complain mode, and '1' if loaded in
 * enforcing mode.
 */
static int
profile_status(const char *str, const int check_enforcing)
{
    char *content = NULL;
    char *tmp = NULL;
    char *etmp = NULL;
    int rc = -2;

    /* create string that is '<str> \0' for accurate matching */
    if (virAsprintf(&tmp, "%s ", str) == -1)
        return rc;

    if (check_enforcing != 0) {
        /* create string that is '<str> (enforce)\0' for accurate matching */
        if (virAsprintf(&etmp, "%s (enforce)", str) == -1) {
            VIR_FREE(tmp);
            return rc;
        }
    }

    if (virFileReadAll(APPARMOR_PROFILES_PATH, MAX_FILE_LEN, &content) < 0) {
        virReportSystemError(errno,
                             _("Failed to read AppArmor profiles list "
                             "\'%s\'"), APPARMOR_PROFILES_PATH);
        goto cleanup;
    }

    if (strstr(content, tmp) != NULL)
        rc = 0;
    else
        rc = -1; /* return -1 if not loaded */
    if (check_enforcing != 0) {
        if (rc == 0 && strstr(content, etmp) != NULL)
            rc = 1;                 /* return '1' if loaded and enforcing */
    }

    VIR_FREE(content);
 cleanup:
    VIR_FREE(tmp);
    VIR_FREE(etmp);

    return rc;
}

static int
profile_loaded(const char *str)
{
    return profile_status(str, 0);
}

/*
 * profile_status_file returns '-1' on error, '0' if file on disk is in
 * complain mode and '1' if file on disk is in enforcing mode
 */
static int
profile_status_file(const char *str)
{
    char *profile = NULL;
    char *content = NULL;
    char *tmp = NULL;
    int rc = -1;
    int len;

    if (virAsprintf(&profile, "%s/%s", APPARMOR_DIR "/libvirt", str) == -1)
        return rc;

    if (!virFileExists(profile))
        goto failed;

    if ((len = virFileReadAll(profile, MAX_FILE_LEN, &content)) < 0) {
        virReportSystemError(errno,
                             _("Failed to read \'%s\'"), profile);
        goto failed;
    }

    /* create string that is ' <str> flags=(complain)\0' */
    if (virAsprintf(&tmp, " %s flags=(complain)", str) == -1)
        goto failed;

    if (strstr(content, tmp) != NULL)
        rc = 0;
    else
        rc = 1;

 failed:
    VIR_FREE(tmp);
    VIR_FREE(profile);
    VIR_FREE(content);

    return rc;
}

/*
 * load (add) a profile. Will create one if necessary
 */
static int
load_profile(virSecurityManagerPtr mgr G_GNUC_UNUSED,
             const char *profile,
             virDomainDefPtr def,
             const char *fn,
             bool append)
{
    int rc = -1;
    bool create = true;
    char *xml = NULL;
    virCommandPtr cmd = NULL;

    xml = virDomainDefFormat(def, NULL, VIR_DOMAIN_DEF_FORMAT_SECURE);
    if (!xml)
        goto cleanup;

    if (profile_status_file(profile) >= 0)
        create = false;

    cmd = virCommandNewArgList(VIRT_AA_HELPER,
                               create ? "-c" : "-r",
                               "-u", profile, NULL);
    if (!create && fn) {
        if (append) {
            virCommandAddArgList(cmd, "-F", fn, NULL);
        } else {
            virCommandAddArgList(cmd, "-f", fn, NULL);
        }
    }

    virCommandAddEnvFormat(cmd,
                           "LIBVIRT_LOG_OUTPUTS=%d:stderr",
                           virLogGetDefaultPriority());

    virCommandSetInputBuffer(cmd, xml);
    rc = virCommandRun(cmd, NULL);

 cleanup:
    VIR_FREE(xml);
    virCommandFree(cmd);

    return rc;
}

static int
remove_profile(const char *profile)
{
    int rc = -1;
    const char * const argv[] = {
        VIRT_AA_HELPER, "-D", "-u", profile, NULL
    };

    if (virRun(argv, NULL) == 0)
        rc = 0;

    return rc;
}

static char *
get_profile_name(virDomainDefPtr def)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char *name = NULL;

    virUUIDFormat(def->uuid, uuidstr);
    if (virAsprintf(&name, "%s%s", AA_PREFIX, uuidstr) < 0)
        return NULL;

    return name;
}

/* returns -1 on error or profile for libvirtd is unconfined, 0 if complain
 * mode and 1 if enforcing. This is required because at present you cannot
 * aa_change_profile() from a process that is unconfined.
 */
static int
use_apparmor(void)
{
    int rc = -1;
    char *libvirt_daemon = NULL;

    if (virFileResolveLink("/proc/self/exe", &libvirt_daemon) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("could not find libvirtd"));
        return rc;
    }

    /* If libvirt_lxc is calling us, then consider apparmor is used
     * and enforced. */
    if (strstr(libvirt_daemon, "libvirt_lxc"))
        return 1;

    if (access(APPARMOR_PROFILES_PATH, R_OK) != 0)
        goto cleanup;

    /* First check profile status using full binary path. If that fails
     * check using profile name.
     */
    rc = profile_status(libvirt_daemon, 1);
    if (rc < 0) {
        rc = profile_status("libvirtd", 1);
        /* Error or unconfined should all result in -1*/
        if (rc < 0)
            rc = -1;
    }

 cleanup:
    VIR_FREE(libvirt_daemon);
    return rc;
}

/* reload the profile, adding read/write file specified by fn if it is not
 * NULL.
 */
static int
reload_profile(virSecurityManagerPtr mgr,
               virDomainDefPtr def,
               const char *fn,
               bool append)
{
    int rc = -1;
    char *profile_name = NULL;
    virSecurityLabelDefPtr secdef = virDomainDefGetSecurityLabelDef(
                                                def, SECURITY_APPARMOR_NAME);

    if (!secdef || !secdef->relabel)
        return 0;

    if ((profile_name = get_profile_name(def)) == NULL)
        return rc;

    /* Update the profile only if it is loaded */
    if (profile_loaded(secdef->imagelabel) >= 0) {
        if (load_profile(mgr, secdef->imagelabel, def, fn, append) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot update AppArmor profile "
                             "\'%s\'"),
                           secdef->imagelabel);
            goto cleanup;
        }
    }

    rc = 0;
 cleanup:
    VIR_FREE(profile_name);

    return rc;
}

static int
AppArmorSetSecurityHostdevLabelHelper(const char *file, void *opaque)
{
    struct SDPDOP *ptr = opaque;
    virDomainDefPtr def = ptr->def;

    return reload_profile(ptr->mgr, def, file, true);
}

static int
AppArmorSetSecurityUSBLabel(virUSBDevicePtr dev G_GNUC_UNUSED,
                            const char *file, void *opaque)
{
    return AppArmorSetSecurityHostdevLabelHelper(file, opaque);
}

static int
AppArmorSetSecurityPCILabel(virPCIDevicePtr dev G_GNUC_UNUSED,
                            const char *file, void *opaque)
{
    return AppArmorSetSecurityHostdevLabelHelper(file, opaque);
}

static int
AppArmorSetSecuritySCSILabel(virSCSIDevicePtr dev G_GNUC_UNUSED,
                             const char *file, void *opaque)
{
    return AppArmorSetSecurityHostdevLabelHelper(file, opaque);
}

static int
AppArmorSetSecurityHostLabel(virSCSIVHostDevicePtr dev G_GNUC_UNUSED,
                             const char *file, void *opaque)
{
    return AppArmorSetSecurityHostdevLabelHelper(file, opaque);
}

/* Called on libvirtd startup to see if AppArmor is available */
static int
AppArmorSecurityManagerProbe(const char *virtDriver G_GNUC_UNUSED)
{
    char *template_qemu = NULL;
    char *template_lxc = NULL;
    int rc = SECURITY_DRIVER_DISABLE;

    if (use_apparmor() < 0)
        return rc;

    /* see if template file exists */
    if (virAsprintf(&template_qemu, "%s/TEMPLATE.qemu",
                               APPARMOR_DIR "/libvirt") == -1)
        return rc;

    if (virAsprintf(&template_lxc, "%s/TEMPLATE.lxc",
                               APPARMOR_DIR "/libvirt") == -1)
        goto cleanup;

    if (!virFileExists(template_qemu)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("template \'%s\' does not exist"), template_qemu);
        goto cleanup;
    }
    if (!virFileExists(template_lxc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("template \'%s\' does not exist"), template_lxc);
        goto cleanup;
    }
    rc = SECURITY_DRIVER_ENABLE;

 cleanup:
    VIR_FREE(template_qemu);
    VIR_FREE(template_lxc);

    return rc;
}

/* Security driver initialization. DOI is for 'Domain of Interpretation' and is
 * currently not used.
 */
static int
AppArmorSecurityManagerOpen(virSecurityManagerPtr mgr G_GNUC_UNUSED)
{
    return 0;
}

static int
AppArmorSecurityManagerClose(virSecurityManagerPtr mgr G_GNUC_UNUSED)
{
    return 0;
}

static const char *
AppArmorSecurityManagerGetModel(virSecurityManagerPtr mgr G_GNUC_UNUSED)
{
    return SECURITY_APPARMOR_NAME;
}

static const char *
AppArmorSecurityManagerGetDOI(virSecurityManagerPtr mgr G_GNUC_UNUSED)
{
    return SECURITY_APPARMOR_VOID_DOI;
}


/* Currently called in qemudStartVMDaemon to setup a 'label'. We look for and
 * use a profile based on the UUID, otherwise create one based on a template.
 * Keep in mind that this is called on 'start' with RestoreSecurityLabel being
 * called on shutdown.
*/
static int
AppArmorGenSecurityLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                         virDomainDefPtr def)
{
    int rc = -1;
    char *profile_name = NULL;
    virSecurityLabelDefPtr secdef = virDomainDefGetSecurityLabelDef(def,
                                                SECURITY_APPARMOR_NAME);

    if (!secdef)
        return 0;

    if ((secdef->type == VIR_DOMAIN_SECLABEL_STATIC) ||
        (secdef->type == VIR_DOMAIN_SECLABEL_NONE))
        return 0;

    if (secdef->baselabel) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("Cannot set a base label with AppArmour"));
        return rc;
    }

    if (secdef->label || secdef->imagelabel) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s",
                       _("security label already defined for VM"));
        return rc;
    }

    if ((profile_name = get_profile_name(def)) == NULL)
        return rc;

    if (VIR_STRDUP(secdef->label, profile_name) < 0)
        goto cleanup;

    /* set imagelabel the same as label (but we won't use it) */
    if (VIR_STRDUP(secdef->imagelabel, profile_name) < 0)
        goto err;

    if (!secdef->model && VIR_STRDUP(secdef->model, SECURITY_APPARMOR_NAME) < 0)
        goto err;

    /* Now that we have a label, load the profile into the kernel. */
    if (load_profile(mgr, secdef->label, def, NULL, false) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot load AppArmor profile "
                       "\'%s\'"), secdef->label);
        goto err;
    }

    rc = 0;
    goto cleanup;

 err:
    VIR_FREE(secdef->label);
    VIR_FREE(secdef->imagelabel);
    VIR_FREE(secdef->model);

 cleanup:
    VIR_FREE(profile_name);

    return rc;
}

static int
AppArmorSetSecurityAllLabel(virSecurityManagerPtr mgr,
                            virDomainDefPtr def,
                            const char *stdin_path,
                            bool chardevStdioLogd G_GNUC_UNUSED,
                            bool migrated G_GNUC_UNUSED)
{
    virSecurityLabelDefPtr secdef = virDomainDefGetSecurityLabelDef(def,
                                                    SECURITY_APPARMOR_NAME);
    if (!secdef || !secdef->relabel)
        return 0;

    /* Reload the profile if stdin_path is specified. Note that
       GenSecurityLabel() will have already been run. */
    if (stdin_path)
        return reload_profile(mgr, def, stdin_path, true);

    return 0;
}

/* Seen with 'virsh dominfo <vm>'. This function only called if the VM is
 * running.
 */
static int
AppArmorGetSecurityProcessLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                                virDomainDefPtr def,
                                pid_t pid G_GNUC_UNUSED,
                                virSecurityLabelPtr sec)
{
    int rc = -1;
    int status;
    char *profile_name = NULL;

    if ((profile_name = get_profile_name(def)) == NULL)
        return rc;

    status = profile_status(profile_name, 1);
    if (status < -1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("error getting profile status"));
        goto cleanup;
    } else if (status == -1) {
        sec->label[0] = '\0';
    } else {
        if (virStrcpy(sec->label, profile_name, VIR_SECURITY_LABEL_BUFLEN) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("error copying profile name"));
            goto cleanup;
        }
    }

    sec->enforcing = status == 1;
    rc = 0;

 cleanup:
    VIR_FREE(profile_name);

    return rc;
}

/* Called on VM shutdown and destroy. See AppArmorGenSecurityLabel (above) for
 * more details. Currently called via qemudShutdownVMDaemon.
 */
static int
AppArmorReleaseSecurityLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                             virDomainDefPtr def)
{
    virSecurityLabelDefPtr secdef = virDomainDefGetSecurityLabelDef(def,
                                                        SECURITY_APPARMOR_NAME);
    if (secdef) {
        VIR_FREE(secdef->model);
        VIR_FREE(secdef->label);
        VIR_FREE(secdef->imagelabel);
    }

    return 0;
}


static int
AppArmorRestoreSecurityAllLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                                virDomainDefPtr def,
                                bool migrated G_GNUC_UNUSED,
                                bool chardevStdioLogd G_GNUC_UNUSED)
{
    int rc = 0;
    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);

    if (!secdef)
        return 0;

    if (secdef->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        if ((rc = remove_profile(secdef->label)) != 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not remove profile for \'%s\'"),
                           secdef->label);
        }
    }
    return rc;
}

/* Called via virCommand hook. Output goes to
 * LOCALSTATEDIR/log/libvirt/qemu/<vm name>.log
 */
static int
AppArmorSetSecurityProcessLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                                virDomainDefPtr def)
{
    int rc = -1;
    char *profile_name = NULL;
    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);

    if (!secdef || !secdef->label)
        return 0;

    if ((profile_name = get_profile_name(def)) == NULL)
        return rc;

    if (STRNEQ(SECURITY_APPARMOR_NAME, secdef->model)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "\'%s\' model configured for domain, but "
                         "hypervisor driver is \'%s\'."),
                       secdef->model, SECURITY_APPARMOR_NAME);
        if (use_apparmor() > 0)
            goto cleanup;
    }

    VIR_DEBUG("Changing AppArmor profile to %s", profile_name);
    if (aa_change_profile(profile_name) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("error calling aa_change_profile()"));
        goto cleanup;
    }
    rc = 0;

 cleanup:
    VIR_FREE(profile_name);

    return rc;
}

/* Called directly by API user prior to virCommandRun().
 * virCommandRun() will then call aa_change_profile() (if a
 * cmd->appArmorProfile has been set) *after forking the child
 * process*.
 */
static int
AppArmorSetSecurityChildProcessLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                                     virDomainDefPtr def,
                                     virCommandPtr cmd)
{
    int rc = -1;
    char *profile_name = NULL;
    char *cmd_str = NULL;
    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);

    if (!secdef || !secdef->label)
        return 0;

    if (STRNEQ(SECURITY_APPARMOR_NAME, secdef->model)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "\'%s\' model configured for domain, but "
                         "hypervisor driver is \'%s\'."),
                       secdef->model, SECURITY_APPARMOR_NAME);
        if (use_apparmor() > 0)
            goto cleanup;
    }

    if ((profile_name = get_profile_name(def)) == NULL)
        goto cleanup;

    cmd_str = virCommandToString(cmd, false);
    VIR_DEBUG("Changing AppArmor profile to %s on %s", profile_name, cmd_str);
    virCommandSetAppArmorProfile(cmd, profile_name);
    rc = 0;

 cleanup:
    VIR_FREE(profile_name);
    VIR_FREE(cmd_str);
    return rc;
}

static int
AppArmorSetSecurityDaemonSocketLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                                     virDomainDefPtr vm G_GNUC_UNUSED)
{
    return 0;
}

static int
AppArmorSetSecuritySocketLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                               virDomainDefPtr def G_GNUC_UNUSED)
{
    return 0;
}

static int
AppArmorClearSecuritySocketLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                                 virDomainDefPtr def G_GNUC_UNUSED)
{
    return 0;
}


/* Called when hotplugging */
static int
AppArmorRestoreSecurityImageLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
                                  virStorageSourcePtr src,
                                  virSecurityDomainImageLabelFlags flags G_GNUC_UNUSED)
{
    if (!virStorageSourceIsLocalStorage(src))
        return 0;

    return reload_profile(mgr, def, NULL, false);
}


/* Called when hotplugging */
static int
AppArmorSetMemoryLabel(virSecurityManagerPtr mgr,
                       virDomainDefPtr def,
                       virDomainMemoryDefPtr mem)
{
    if (mem == NULL)
        return 0;

    switch ((virDomainMemoryModel) mem->model) {
    case VIR_DOMAIN_MEMORY_MODEL_NVDIMM:
        if (mem->nvdimmPath == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s: nvdimm without a path"),
                           __func__);
            return -1;
        }
        if (!virFileExists(mem->nvdimmPath)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s: \'%s\' does not exist"),
                           __func__, mem->nvdimmPath);
            return -1;
        }
        return reload_profile(mgr, def, mem->nvdimmPath, true);
        break;
    case VIR_DOMAIN_MEMORY_MODEL_NONE:
    case VIR_DOMAIN_MEMORY_MODEL_DIMM:
    case VIR_DOMAIN_MEMORY_MODEL_LAST:
        break;
    }

    return 0;
}


static int
AppArmorRestoreMemoryLabel(virSecurityManagerPtr mgr,
                           virDomainDefPtr def,
                           virDomainMemoryDefPtr mem G_GNUC_UNUSED)
{
    return reload_profile(mgr, def, NULL, false);
}

/* Called when hotplugging */
static int
AppArmorSetInputLabel(virSecurityManagerPtr mgr,
                      virDomainDefPtr def,
                      virDomainInputDefPtr input)
{
    if (input == NULL)
        return 0;

    switch ((virDomainInputType)input->type) {
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
        if (input->source.evdev == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s: passthrough input device has no source"),
                           __func__);
            return -1;
        }
        if (!virFileExists(input->source.evdev)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s: \'%s\' does not exist"),
                           __func__, input->source.evdev);
            return -1;
        }
        return reload_profile(mgr, def, input->source.evdev, true);
        break;

    case VIR_DOMAIN_INPUT_TYPE_MOUSE:
    case VIR_DOMAIN_INPUT_TYPE_TABLET:
    case VIR_DOMAIN_INPUT_TYPE_KBD:
    case VIR_DOMAIN_INPUT_TYPE_LAST:
        break;
    }

    return 0;
}


static int
AppArmorRestoreInputLabel(virSecurityManagerPtr mgr,
                          virDomainDefPtr def,
                          virDomainInputDefPtr input G_GNUC_UNUSED)
{
    return reload_profile(mgr, def, NULL, false);
}

/* Called when hotplugging */
static int
AppArmorSetSecurityImageLabel(virSecurityManagerPtr mgr,
                              virDomainDefPtr def,
                              virStorageSourcePtr src,
                              virSecurityDomainImageLabelFlags flags G_GNUC_UNUSED)
{
    int rc = -1;
    char *profile_name = NULL;
    virSecurityLabelDefPtr secdef;

    if (!src->path || !virStorageSourceIsLocalStorage(src))
        return 0;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);
    if (!secdef || !secdef->relabel)
        return 0;

    if (secdef->imagelabel) {
        /* if the device doesn't exist, error out */
        if (!virFileExists(src->path)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("\'%s\' does not exist"),
                           src->path);
            return -1;
        }

        if ((profile_name = get_profile_name(def)) == NULL)
            return -1;

        /* update the profile only if it is loaded */
        if (profile_loaded(secdef->imagelabel) >= 0) {
            if (load_profile(mgr, secdef->imagelabel, def,
                             src->path, false) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot update AppArmor profile "
                                 "\'%s\'"),
                               secdef->imagelabel);
                goto cleanup;
            }
        }
    }
    rc = 0;

 cleanup:
    VIR_FREE(profile_name);

    return rc;
}

static int
AppArmorSecurityVerify(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                       virDomainDefPtr def)
{
    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);

    if (!secdef)
        return 0;

    if (secdef->type == VIR_DOMAIN_SECLABEL_STATIC) {
        if (use_apparmor() < 0 || profile_status(secdef->label, 0) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid security label \'%s\'"),
                           secdef->label);
            return -1;
        }
    }
    return 0;
}

static int
AppArmorReserveSecurityLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                             virDomainDefPtr def G_GNUC_UNUSED,
                             pid_t pid G_GNUC_UNUSED)
{
    /* NOOP. Nothing to reserve with AppArmor */
    return 0;
}

static int
AppArmorSetSecurityHostdevLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def,
                                virDomainHostdevDefPtr dev,
                                const char *vroot)
{
    struct SDPDOP *ptr;
    int ret = -1;
    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
    virDomainHostdevSubsysSCSIVHostPtr hostsrc = &dev->source.subsys.u.scsi_host;
    virDomainHostdevSubsysMediatedDevPtr mdevsrc = &dev->source.subsys.u.mdev;

    if (!secdef || !secdef->relabel)
        return 0;

    if (dev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
        return 0;

    /* Like AppArmorRestoreSecurityImageLabel() for a networked disk,
     * do nothing for an iSCSI hostdev
     */
    if (dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
        return 0;

    if (profile_loaded(secdef->imagelabel) < 0)
        return 0;

    if (VIR_ALLOC(ptr) < 0)
        return -1;
    ptr->mgr = mgr;
    ptr->def = def;

    switch ((virDomainHostdevSubsysType)dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
        virUSBDevicePtr usb =
            virUSBDeviceNew(usbsrc->bus, usbsrc->device, vroot);
        if (!usb)
            goto done;

        ret = virUSBDeviceFileIterate(usb, AppArmorSetSecurityUSBLabel, ptr);
        virUSBDeviceFree(usb);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
        virPCIDevicePtr pci =
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);

        if (!pci)
            goto done;

        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);

            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
                goto done;
            }
            ret = AppArmorSetSecurityPCILabel(pci, vfioGroupDev, ptr);
            VIR_FREE(vfioGroupDev);
        } else {
            ret = virPCIDeviceFileIterate(pci, AppArmorSetSecurityPCILabel, ptr);
        }
        virPCIDeviceFree(pci);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
        virSCSIDevicePtr scsi =
            virSCSIDeviceNew(NULL,
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
                             dev->readonly, dev->shareable);

         if (!scsi)
             goto done;

        ret = virSCSIDeviceFileIterate(scsi, AppArmorSetSecuritySCSILabel, ptr);
        virSCSIDeviceFree(scsi);

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST: {
        virSCSIVHostDevicePtr host = virSCSIVHostDeviceNew(hostsrc->wwpn);

        if (!host)
            goto done;

        ret = virSCSIVHostDeviceFileIterate(host,
                                            AppArmorSetSecurityHostLabel,
                                            ptr);
        virSCSIVHostDeviceFree(host);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV: {
        char *vfiodev = NULL;

        if (!(vfiodev = virMediatedDeviceGetIOMMUGroupDev(mdevsrc->uuidstr)))
            goto done;

        ret = AppArmorSetSecurityHostdevLabelHelper(vfiodev, ptr);

        VIR_FREE(vfiodev);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
        ret = 0;
        break;
    }

 done:
    VIR_FREE(ptr);
    return ret;
}


static int
AppArmorRestoreSecurityHostdevLabel(virSecurityManagerPtr mgr,
                                    virDomainDefPtr def,
                                    virDomainHostdevDefPtr dev G_GNUC_UNUSED,
                                    const char *vroot G_GNUC_UNUSED)

{
    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);

    if (!secdef || !secdef->relabel)
        return 0;

    return reload_profile(mgr, def, NULL, false);
}

static int
AppArmorSetChardevLabel(virSecurityManagerPtr mgr,
                        virDomainDefPtr def,
                        virDomainChrSourceDefPtr dev_source,
                        bool chardevStdioLogd G_GNUC_UNUSED)
{
    char *in = NULL, *out = NULL;
    int ret = -1;
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);
    if (!secdef)
        return 0;

    switch ((virDomainChrType)dev_source->type) {
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
    case VIR_DOMAIN_CHR_TYPE_UNIX:
    case VIR_DOMAIN_CHR_TYPE_PTY:
        ret = reload_profile(mgr, def, dev_source->data.file.path, true);
        break;

    case VIR_DOMAIN_CHR_TYPE_PIPE:
        if (virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0 ||
            virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0)
            goto done;
        if (virFileExists(in)) {
            if (reload_profile(mgr, def, in, true) < 0)
                goto done;
        }
        if (virFileExists(out)) {
            if (reload_profile(mgr, def, out, true) < 0)
                goto done;
        }
        ret = reload_profile(mgr, def, dev_source->data.file.path, true);
        break;

    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
    case VIR_DOMAIN_CHR_TYPE_NULL:
    case VIR_DOMAIN_CHR_TYPE_VC:
    case VIR_DOMAIN_CHR_TYPE_STDIO:
    case VIR_DOMAIN_CHR_TYPE_UDP:
    case VIR_DOMAIN_CHR_TYPE_TCP:
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
    case VIR_DOMAIN_CHR_TYPE_NMDM:
    case VIR_DOMAIN_CHR_TYPE_LAST:
        ret = 0;
        break;
    }

 done:
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}

static int
AppArmorRestoreChardevLabel(virSecurityManagerPtr mgr,
                            virDomainDefPtr def,
                            virDomainChrSourceDefPtr dev_source G_GNUC_UNUSED,
                            bool chardevStdioLogd G_GNUC_UNUSED)
{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);
    if (!secdef)
        return 0;

    return reload_profile(mgr, def, NULL, false);
}

static int
AppArmorSetSavedStateLabel(virSecurityManagerPtr mgr,
                           virDomainDefPtr def,
                           const char *savefile)
{
    return reload_profile(mgr, def, savefile, true);
}

static int
AppArmorSetPathLabel(virSecurityManagerPtr mgr,
                           virDomainDefPtr def,
                           const char *path,
                           bool allowSubtree)
{
    int rc = -1;
    char *full_path = NULL;

    if (allowSubtree) {
        if (virAsprintf(&full_path, "%s/{,**}", path) < 0)
            return -1;
        rc = reload_profile(mgr, def, full_path, true);
        VIR_FREE(full_path);
    } else {
        rc = reload_profile(mgr, def, path, true);
    }

    return rc;
}

static int
AppArmorRestoreSavedStateLabel(virSecurityManagerPtr mgr,
                               virDomainDefPtr def,
                               const char *savefile G_GNUC_UNUSED)
{
    return reload_profile(mgr, def, NULL, false);
}

static int
AppArmorSetFDLabel(virSecurityManagerPtr mgr,
                   virDomainDefPtr def,
                   int fd)
{
    int rc = -1;
    char *proc = NULL;
    char *fd_path = NULL;

    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_APPARMOR_NAME);

    if (!secdef || !secdef->imagelabel)
        return 0;

    if (virAsprintf(&proc, "/proc/self/fd/%d", fd) == -1)
        return rc;

    if (virFileResolveLink(proc, &fd_path) < 0) {
        /* it's a deleted file, presumably.  Ignore? */
        VIR_WARN("could not find path for descriptor %s, skipping", proc);
        return 0;
    }

    return reload_profile(mgr, def, fd_path, true);
}

static char *
AppArmorGetMountOptions(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                        virDomainDefPtr vm G_GNUC_UNUSED)
{
    char *opts;

    opts = g_strdup("");
    return opts;
}

static const char *
AppArmorGetBaseLabel(virSecurityManagerPtr mgr G_GNUC_UNUSED,
                     int virtType G_GNUC_UNUSED)
{
    return NULL;
}

virSecurityDriver virAppArmorSecurityDriver = {
    .privateDataLen                     = 0,
    .name                               = SECURITY_APPARMOR_NAME,
    .probe                              = AppArmorSecurityManagerProbe,
    .open                               = AppArmorSecurityManagerOpen,
    .close                              = AppArmorSecurityManagerClose,

    .getModel                           = AppArmorSecurityManagerGetModel,
    .getDOI                             = AppArmorSecurityManagerGetDOI,

    .domainSecurityVerify               = AppArmorSecurityVerify,

    .domainSetSecurityImageLabel        = AppArmorSetSecurityImageLabel,
    .domainRestoreSecurityImageLabel    = AppArmorRestoreSecurityImageLabel,

    .domainSetSecurityMemoryLabel       = AppArmorSetMemoryLabel,
    .domainRestoreSecurityMemoryLabel   = AppArmorRestoreMemoryLabel,

    .domainSetSecurityInputLabel        = AppArmorSetInputLabel,
    .domainRestoreSecurityInputLabel    = AppArmorRestoreInputLabel,

    .domainSetSecurityDaemonSocketLabel = AppArmorSetSecurityDaemonSocketLabel,
    .domainSetSecuritySocketLabel       = AppArmorSetSecuritySocketLabel,
    .domainClearSecuritySocketLabel     = AppArmorClearSecuritySocketLabel,

    .domainGenSecurityLabel             = AppArmorGenSecurityLabel,
    .domainReserveSecurityLabel         = AppArmorReserveSecurityLabel,
    .domainReleaseSecurityLabel         = AppArmorReleaseSecurityLabel,

    .domainGetSecurityProcessLabel      = AppArmorGetSecurityProcessLabel,
    .domainSetSecurityProcessLabel      = AppArmorSetSecurityProcessLabel,
    .domainSetSecurityChildProcessLabel = AppArmorSetSecurityChildProcessLabel,

    .domainSetSecurityAllLabel          = AppArmorSetSecurityAllLabel,
    .domainRestoreSecurityAllLabel      = AppArmorRestoreSecurityAllLabel,

    .domainSetSecurityHostdevLabel      = AppArmorSetSecurityHostdevLabel,
    .domainRestoreSecurityHostdevLabel  = AppArmorRestoreSecurityHostdevLabel,

    .domainSetSavedStateLabel           = AppArmorSetSavedStateLabel,
    .domainRestoreSavedStateLabel       = AppArmorRestoreSavedStateLabel,

    .domainSetPathLabel                 = AppArmorSetPathLabel,

    .domainSetSecurityChardevLabel      = AppArmorSetChardevLabel,
    .domainRestoreSecurityChardevLabel  = AppArmorRestoreChardevLabel,

    .domainSetSecurityImageFDLabel      = AppArmorSetFDLabel,
    .domainSetSecurityTapFDLabel        = AppArmorSetFDLabel,

    .domainGetSecurityMountOptions      = AppArmorGetMountOptions,

    .getBaseLabel                       = AppArmorGetBaseLabel,
};