Search code examples
linux-kernelparallel-port

Write to /dev/port as non-root user


I am working on a rather complex C++ code which performs the following operation as standard user

fd = open("/dev/port",O_WRONLY);
...
lseek(fd, 0x2E,SEEK_SET);
...
write(fd,&buf,1);

I get a 'Operation not permitted' error on opening the file, despite having chmodded the file.

crwxrwxrwx 1 root kmem 1, 4 Sep 12 14:32 /dev/port

I know of security issues with chmodding /dev/port, but as far as we're concerned the system will run on a closed LAN.


To make it easier, this:

using namespace std;
int main(int argc, char *argv[])
{
  int fd=-1;

  //  fd1=open("/dev/port",O_RDWR|O_NDELAY);
  vector<string> fnames;
  fnames.push_back("/dev/port");
  fnames.push_back("/dev/tty0");

  string fname;


  for(int i=0;i<fnames.size();i++)
    {
      fname = fnames[i];
      fd=open(fname.c_str(),O_RDWR | O_NDELAY);
      if(fd<0)
    {
      cout << fname << " "  << fd << endl;
      cout << fname << " "  << strerror(errno) << endl;
    }
      else
    {
      cout << "Open ok: " << fname << endl;
    }
    }


  return 0;
}

returns this:

me@myPC:~/test$ ./main 
/dev/port -1
/dev/port Operation not permitted
Open ok: /dev/tty0

with these permission rights

me@myPC:~/test$ ll /dev/tty /dev/port 
crw-rw-rw- 1 root kmem 1, 4 Sep 12 14:32 /dev/port
crw-rw-rw- 1 root tty  5, 0 Sep 12 15:51 /dev/tty

Solution

  • To open /dev/port you need the capability CAP_SYS_RAWIO, in addition to permission to open the file.

    drivers/char/mem.c:730
    
    static int open_port(struct inode * inode, struct file * filp)
    {
        return capable(CAP_SYS_RAWIO) ? 0 : -EPERM;
    }
    

    You can either gain this by being root or by setting it for a single executable (similar to set-uid) using setcap.

    http://linux.die.net/man/8/setcap