File: policy.c

package info (click to toggle)
pmount 0.8-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 340 kB
  • ctags: 95
  • sloc: ansic: 1,396; makefile: 48; sh: 24
file content (471 lines) | stat: -rw-r--r-- 14,303 bytes parent folder | download
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
/**
 * policy.c - functions for testing various policy parts for pmount
 *
 * Author: Martin Pitt <martin.pitt@canonical.com>
 * (c) 2004 Canonical Ltd.
 *
 * This software is distributed under the terms and conditions of the 
 * GNU General Public License. See file GPL for the full text of the license.
 */

#include "policy.h"
#include "utils.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mntent.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <libintl.h>
#include <sys/stat.h>
#include <sysfs/libsysfs.h>
#include <regex.h>

/*************************************************************************
 *
 * Sysfs query functions for determining if a device is removable
 *
 *************************************************************************/


/**
 * Check whether a bus occurs anywhere in the ancestry of a device.
 * @param dev sysfs device
 * @param buses NULL-terminated array of bus names to scan for
 * @return 0 if not found, 1 if found
 */
int
find_bus_ancestry( struct sysfs_device* dev, char** buses ) {
    char **i;

    if( !dev || !buses )
        return 0;

    for( i = buses; *i; ++i ) {
        if( !strcmp( dev->bus, *i ) )
            return 1;
    }

    return find_bus_ancestry( sysfs_get_device_parent( dev ), buses );
}

/**
 * Find sysfs node that matches the major and minor device number of the given
 * device. Exit the process immediately on errors.
 * @param dev device node to search for (e. g. /dev/sda1)
 * @param blockdevpath if not NULL, the corresponding /sys/block/<drive>/ path
 *        is written into this buffer; this can be used to query additional
 *        attributes
 * @param blockdevpathsize size of blockdevpath buffer (if not NULL)
 * @return Matching sysfs_device node (NULL if not found)
 */
struct sysfs_device*
find_sysfs_device( const char* dev, char* blockdevpath, size_t blockdevpathsize ) {
    unsigned char devmajor, devminor;
    unsigned char sysmajor, sysminor;
    char mntpath[PATH_MAX];
    char blockdirname[255];
    char devdirname[512]; // < 255 chars blockdir + max. 255 chars subdir
    char devfilename[PATH_MAX];
    char linkfilename[1024];
    DIR *devdir, *partdir;
    struct dirent *devdirent, *partdirent;
    struct sysfs_device *sysdev = NULL;
    struct stat devstat;
    
    /* determine major and minor of dev */
    if( stat( dev, &devstat ) ) {
        perror( _("Error: could not get status of device") );
        exit( -1 );
    }
    devmajor = (unsigned char) ( devstat.st_rdev >> 8 );
    devminor = (unsigned char) ( devstat.st_rdev & 255 );

    debug( "find_sysfs_device: looking for sysfs directory for device %u:%u\n",
                (unsigned) devmajor, (unsigned) devminor );

    /* get /sys/block/ */
    if( sysfs_get_mnt_path( mntpath, sizeof(mntpath) ) ) {
        fputs( _("Error: could not get sysfs directory\n"), stderr );
        exit( -1 );
    }
    snprintf( blockdirname, sizeof( blockdirname ), "%s/block/", mntpath );

    devdir = opendir( blockdirname );
    if( !devdir ) {
        perror( _("Error: could not open <sysfs dir>/block/") );
        exit( -1 );
    }

    /* open each subdirectory and see whether major device matches */
    while( ( devdirent = readdir( devdir ) ) != NULL ) {
        /* construct /sys/block/<device> */
        snprintf( devdirname, sizeof( devdirname ), "%s%s", blockdirname, devdirent->d_name );

        /* construct /sys/block/<device>/dev */
        snprintf( devfilename, sizeof( devfilename ), "%s%s", devdirname, "/dev" );

        /* read the block device major:minor */
        if( read_number_colon_number( devfilename, &sysmajor, &sysminor ) == -1 )
            continue;

        debug( "find_sysfs_device: checking whether %s is on %s (%u:%u)\n",
                    dev, devdirname, (unsigned) sysmajor, (unsigned) sysminor );

        if( sysmajor == devmajor ) {
            debug( "find_sysfs_device: major device numbers match");

            /* if dev is a partition, check that there is a subdir that matches
             * the partition */
            if( sysminor != devminor ) {
                int found_part = 0;
                
                debug( "find_sysfs_device: minor device numbers do not match, checking partitions...");

                partdir = opendir( devdirname );
                if( !partdir ) {
                    perror( _("Error: could not open <sysfs dir>/block/<device>/") );
                    exit( -1 );
                }
                while( ( partdirent = readdir( partdir ) ) != NULL ) {
                    if( partdirent->d_type != DT_DIR )
                        continue;

                    /* construct /sys/block/<device>/<partition>/dev */
                    snprintf( devfilename, sizeof( devfilename ), "%s/%s/%s",
                            devdirname, partdirent->d_name, "dev" );

                    /* read the block device major:minor */
                    if( read_number_colon_number( devfilename, &sysmajor, &sysminor ) == -1 )
                        continue;

                    debug( "find_sysfs_device: checking whether device %s matches partition %u:%u\n",
                                dev, (unsigned) sysmajor, (unsigned) sysminor );

                    if( sysmajor == devmajor && sysminor == devminor ) {
                        debug( "find_sysfs_device: -> partition matches, belongs to block device %s\n",
                                    devdirname );
                        found_part = 1;
                        break;
                    }
                } 

                closedir( partdir );

                if( !found_part ) {
                    /* dev is a partition, but it does not belong to the
                     * currently examined device; skip to next device */
                    continue;
                }
            } else
                debug( "find_sysfs_device: minor device numbers also match, %s is a raw device\n",
                            dev );


            snprintf( devfilename, sizeof( devfilename ), "%s/device", devdirname );

            /* read out the link */
            if( !sysfs_get_link( devfilename, linkfilename, 1024 ) )
                sysdev = sysfs_open_device_path( linkfilename );

            /* return /sys/block/<drive> if requested */
            if( blockdevpath )
                snprintf( blockdevpath, blockdevpathsize, "%s", devdirname );
            break;
        }
    }

    closedir( devdir );

    return sysdev;
}

/**
 * Return whether attribute attr in blockdevpath exists and has value '1'.
 */
int
get_blockdev_attr( const char* blockdevpath, const char* attr )
{
    char path[PATH_MAX];
    FILE* f;
    int result;
    char value;

    snprintf( path, sizeof( path ), "%s/%s", blockdevpath, attr );

    f = fopen( path, "r" );
    if( !f ) {
        debug( "get_blockdev_attr: could not open %s\n", path );
        return 0;
    }

    result = fread( &value, 1, 1, f );
    fclose( f );

    if( result != 1 ) {
        debug( "get_blockdev_attr: could not read %s\n", path );
        return 0;
    }

    debug( "get_blockdev_attr: value of %s == %c\n", path, value );

    return value == '1';
}

/*************************************************************************
 *
 * Policy functions
 *
 *************************************************************************/

int
device_valid( const char* device )
{
    struct stat st;

    if( stat( device, &st ) ) {
        fprintf( stderr, _("Error: device %s does not exist\n"), device );
        return 0;
    }

    if( !S_ISBLK( st.st_mode ) ) {
        fprintf( stderr, _("Error: %s is not a block device\n"), device );
        return 0;
    }

    return 1;
}

const char*
fstab_has_device( const char* fname, const char* device, char* mntpt, int *uid )
{
    FILE* f;
    struct mntent *entry;
    char pathbuf[PATH_MAX];
    static char fstab_device[PATH_MAX];
    char* realdev;
    char* uidopt;

    if( !( f = fopen( fname, "r" ) ) ) {
        perror( _("Error: could not open fstab-type file") );
        exit( 100 );
    }

    while( ( entry = getmntent( f ) ) != NULL ) {
        snprintf( fstab_device, sizeof( fstab_device ), "%s", entry->mnt_fsname );

        if( realpath( fstab_device, pathbuf ) )
            realdev = pathbuf;
        else
            realdev = fstab_device;

        if( !strcmp( realdev, device ) ) {
                endmntent( f );
                if( mntpt ) {
                    snprintf( mntpt, MEDIA_STRING_SIZE-1, "%s", entry->mnt_dir );
                }
                if( uid ) {
                    uidopt = hasmntopt( entry, "uid" );
                    if( uidopt )
                        uidopt = strchr( uidopt, '=' );
                    if( uidopt ) {
                        ++uidopt; /* skip the '=' */
                        /* FIXME: this probably needs more checking */
                        *uid = atoi( uidopt );
                    } else
                        *uid = -1;
                }
                return fstab_device;
        }
    }

    /* just for safety */
    if( mntpt )
        *mntpt = 0; 

    endmntent( f );
    return NULL;
}

int
fstab_has_mntpt( const char* fname, const char* mntpt, char* device, size_t device_size )
{
    FILE* f;
    struct mntent *entry;
    char realmntptbuf[PATH_MAX];
    char fstabmntptbuf[PATH_MAX];
    const char* realmntpt, *fstabmntpt;

    /* resolve symlinks, if possible */
    if( realpath( mntpt, realmntptbuf ) )
        realmntpt = realmntptbuf;
    else
        realmntpt = mntpt;

    if( !( f = fopen( fname, "r" ) ) ) {
        perror( _("Error: could not open fstab-type file") );
        exit( 100 );
    }

    while( ( entry = getmntent( f ) ) != NULL ) {
        /* resolve symlinks, if possible */
        if( realpath( entry->mnt_dir, fstabmntptbuf ) )
            fstabmntpt = fstabmntptbuf;
        else
            fstabmntpt = entry->mnt_dir;

        if( !strcmp( fstabmntpt, realmntpt ) ) {
            if( device )
                snprintf( device, device_size, "%s", entry->mnt_fsname );
            endmntent( f );
            return 1;
        }
    }

    endmntent( f );
    return 0;
}

int
device_mounted( const char* device, int expect, char* mntpt )
{
    char mp[MEDIA_STRING_SIZE];
    int uid;
    int mounted = fstab_has_device( "/etc/mtab", device, mp, &uid ) ||
                  fstab_has_device( "/proc/mounts", device, mp, &uid );
    if( mounted && !expect )
        fprintf( stderr, _("Error: device %s is already mounted to %s\n"), device, mp );
    else if( !mounted && expect )
        fprintf( stderr, _("Error: device %s is not mounted\n"), device );
    if( mounted && expect && uid >= 0 && (uid_t) uid != getuid() && getuid() > 0) {
        fprintf( stderr, _("Error: device %s was not mounted by you\n"), device );
        return 0;
    }

    if( mntpt )
        snprintf( mntpt, MEDIA_STRING_SIZE-1, "%s", mp );

    return mounted;
}

int
device_removable( const char* device )
{
    struct sysfs_device *dev;
    static char* hotplug_buses[] = { "usb", "ieee1394", NULL };
    int removable;
    char blockdevpath[PATH_MAX];

    dev = find_sysfs_device( device, blockdevpath, sizeof( blockdevpath ) );
    if( !dev ) {
        debug( "device_removable: could not find a sysfs device for %s\n", device );
        return 0; 
    }

    debug( "device_removable: corresponding block device for %s is %s\n",
                device, blockdevpath );

    /* check whether device has "removable" attribute with value '1' */
    removable = get_blockdev_attr( blockdevpath, "removable" );

    /* if not, fall back to bus scanning (regard USB and FireWire as removable) */
    if( !removable )
        removable = find_bus_ancestry( dev, hotplug_buses );
    sysfs_close_device( dev );

    if( !removable )
        fprintf( stderr, _("Error: device %s is not removable\n"), device );
    
    return removable;
}

int
device_whitelisted( const char* device )
{
    FILE* fwl;
    char line[1024];
    char *d;
    regex_t re;
    regmatch_t match[3];

    fwl = fopen( WHITELIST, "r" );
    if( !fwl )
        return 0;

    if( regcomp( &re, "^[[:space:]]*([a-zA-Z0-9/_+\\-\\.]+)[[:space:]]*(#.*)?$", REG_EXTENDED ) ) {
        fprintf( stderr, "Internal error: device_whitelisted(): could not compile regex\n" );
        exit( -1 );
    }

    debug( "device_whitelist: checking " WHITELIST "...\n" );

    while( fgets( line, sizeof( line ), fwl ) ) {
        /* ignore lines which are too long */
        if( strlen( line ) == sizeof( line ) - 1 ) {
            debug ("ignoring invalid oversized line\n");
            continue;
        }

       if (!regexec (&re, line, 3, match, 0)) {
           line[match[1].rm_eo] = 0;
           d = line+match[1].rm_so;
           debug( "comparing %s against whitelisted '%s'\n", device, d);
           if( !strcmp( d, device ) ) {
               debug( "device_whitlisted(): match, returning 1\n" );
               fclose( fwl );
               return 1;
           }
       }
    }

    fclose( fwl );
   debug( "device_whitlisted(): nothing matched, returning 0\n" );
    return 0;
}

int 
device_locked( const char* device )
{
    char lockdirname[PATH_MAX];
    int locked;

    make_lockdir_name( device, lockdirname, sizeof( lockdirname ) );
    locked = is_dir( lockdirname );

    if( locked )
        fprintf( stderr, _("Error: device %s is locked\n"), device );

    return locked;
}

int
mntpt_valid( const char* mntpt ) 
{
    return !assert_dir( mntpt, 1 ) && !assert_emptydir( mntpt );
}

int
mntpt_mounted( const char* mntpt, int expect )
{
    int mounted = fstab_has_mntpt( "/etc/mtab", mntpt, NULL, 0 ) ||
                  fstab_has_mntpt( "/proc/mounts", mntpt, NULL, 0 );

    if( mounted && !expect )
        fprintf( stderr, _("Error: directory %s already contains a mounted file system\n"), mntpt );
    else if( !mounted && expect )
        fprintf( stderr, _("Error: directory %s does not contain a mounted file system\n"), mntpt );

    return mounted;
}

void make_lockdir_name( const char* device, char* name, size_t name_size )
{
    char* devname;

    devname = strreplace( device, '/', '_' );
    snprintf( name, name_size, "%s%s", LOCKDIR, devname );
    free( devname );
}