source: src-qt4/PCDM/src/pcdm-xprocess.cpp @ a51a897

releng/10.0.1releng/10.0.2
Last change on this file since a51a897 was a51a897, checked in by Ken Moore <ken@…>, 5 months ago

Make sure that we run "setlogin(username)" on the login session in PCDM as well before dropping privileges.

  • Property mode set to 100644
File size: 10.4 KB
Line 
1/* PCDM Login Manager:
2*  Written by Ken Moore (ken@pcbsd.org) 2012/2013
3*  Modified by Kris Moore (kris@pcbsd.org) 2013
4*  Copyright(c) 2013 by the PC-BSD Project
5*  Available under the 3-clause BSD license
6*/
7
8#include <sys/types.h>
9#include <sys/wait.h>
10#include <unistd.h>
11#include <pwd.h>
12#include <login_cap.h>
13#include <QMessageBox>
14
15/*
16Sub-classed QProcess for starting an XSession Process
17*/
18
19#include "pcdm-xprocess.h"
20
21XProcess::XProcess() : QProcess(0) {
22  //initialize the variables
23  xuser.clear();
24  xcmd.clear();
25  xhome.clear();
26  xpwd.clear();
27  xshell.clear();
28  pam_started = FALSE;
29  pam_session_open = FALSE;
30  //Setup the finished signal/slot
31  //connect( this, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotCleanup()) );
32}
33
34XProcess::~XProcess(){
35  if( isRunning() ){
36    this->terminate();
37  }
38  this->close();
39}
40
41void XProcess::loginToXSession(QString username, QString password, QString desktop, QString lang){
42  //Setup the variables
43  xuser = username;
44  xpwd = password;
45  xhome = Backend::getUserHomeDir(xuser);
46  xcmd = Backend::getDesktopBinary(desktop);
47  xshell = Backend::getUserShell(xuser);
48  xde = desktop;
49  xlang = lang;
50  //Now start the login process
51  startXSession();
52}
53
54bool XProcess::isRunning(){
55  if(this->state() != QProcess::NotRunning){ return TRUE; }
56  else{ return FALSE; }
57}
58
59void XProcess::waitForSessionClosed(){
60  // CAUTION!!
61  // This function will pause the calling program to wait for the session to end!
62  if( isRunning() ){ this->waitForFinished(-1); }
63
64}
65
66/*
67 ========== SESSION STARTUP ==========
68*/
69
70bool XProcess::startXSession(){
71  //disconnect(SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotCleanup()) );
72  //Check that the necessary info to start the session is available
73  if( xuser.isEmpty() || xcmd.isEmpty() || xhome.isEmpty() || xde.isEmpty() ){
74    emit InvalidLogin();  //Make sure the GUI knows that it was a failure
75    return FALSE;
76  }
77  //Backend::log("Starting up Desktop environment ("+xcmd+") as user ("+xuser+")");
78 
79  //Check for PAM username/password validity
80  if( !pam_checkPW() ){ emit InvalidLogin(); pam_shutdown(); return FALSE; }
81
82
83  //Save the current user/desktop as the last login
84  Backend::saveLoginInfo(Backend::getDisplayNameFromUsername(xuser),xde);
85
86  // Get the users uid/gid information
87  struct passwd *pw;
88  int uid;
89  char *ok;
90
91  if (!(pw = getpwnam(xuser.toLatin1()))) {
92      uid = strtol(xuser.toLatin1(), &ok, 10);
93      if (!(pw = getpwuid(uid))) {
94          emit InvalidLogin();  //Make sure the GUI knows that it was a failure
95          return FALSE;
96      }
97  }
98
99  // Get the environment before we drop priv
100  this->setProcessEnvironment( QProcessEnvironment::systemEnvironment() ); //current environment
101  //Emit the last couple logs before dropping privileges
102  Backend::log("Starting session:");
103  Backend::log(" - Session Log: ~/.pcdm-startup.log");
104  //Now allow this user access to the Xserver
105  QString xhostcmd = "xhost si:localuser:"+xuser;
106  system(xhostcmd.toUtf8());
107  //And finally set the login user before dropping priv
108  setlogin( xuser.toUtf8() );
109  //QWidget *wid = new QWidget();
110  if (setgid(pw->pw_gid) < 0) {
111      qDebug() << "setgid() failed!";
112      emit InvalidLogin();  //Make sure the GUI knows that it was a failure
113      return FALSE;
114  }
115
116  // Setup our other groups
117  if (initgroups(xuser.toLatin1(), pw->pw_gid) < 0) {
118      qDebug() << "initgroups() failed!";
119      emit InvalidLogin();  //Make sure the GUI knows that it was a failure
120      setgid(0);
121      return FALSE;
122  }
123
124  // Lets drop to user privs
125  if (setuid(pw->pw_uid) < 0) {
126      qDebug() << "setuid() failed!";
127      emit InvalidLogin();  //Make sure the GUI knows that it was a failure
128      return FALSE;
129  }
130  //Startup the PAM session
131  if( !pam_startSession() ){ pam_shutdown(); return FALSE; }
132  pam_session_open = TRUE; //flag that pam has an open session
133  QString cmd;
134  // Configure the DE startup command
135
136  //  - Add the DE startup command to the end
137  cmd.append("dbus-launch --exit-with-session "+xcmd);
138  //cmd.append(xcmd);
139
140  //Backend::log("Startup command: "+cmd);
141  // Setup the process environment
142  setupSessionEnvironment();
143  //Log the DE startup outputs as well
144  this->setProcessChannelMode(QProcess::MergedChannels);
145  this->setStandardOutputFile(xhome+"/.pcdm-startup.log",QIODevice::Truncate);
146  //this->setStandardErrorFile(xhome+"/.pcdm-startup.err",QIODevice::Truncate);
147  // Startup the process(s)
148   //  - Setup to run the user's <home-dir>/.xprofile startup script
149  if(QFile::exists(xhome+"/.xprofile")){
150    //Make sure the file is executable
151    QFile::setPermissions(xhome+"/.xprofile", QFile::permissions(xhome+"/.xprofile") | QFile::ExeOwner | QFile::ExeGroup | QFile::ExeOther );
152    //Need to run a couple commands in sequence: so put them in a script file
153    QStringList contents;
154    contents << ". "+xhome+"/.xprofile";
155    contents << cmd; //end with the actual command for the DE
156    contents << "exit $?"; //Make sure we return the DE return value
157    if( Backend::writeFile(xhome+"/.pcdmsessionstart", contents) ){
158      //script created fine, change the command to just run it
159      cmd = "sh "+xhome+"/.pcdmsessionstart";
160    }else{
161      //Could not create script file, fallback on running them seperately
162      QString xpro = "sh "+xhome+"/.xprofile";
163      this->start(xpro);
164      this->waitForFinished(3000);
165    }
166  }
167  connect( this, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotCleanup()) );
168  this->start(cmd);
169  return TRUE;
170}
171
172void XProcess::slotCleanup(){
173  Backend::log("Session Finished\n - Return Code: "+ QString::number(this->exitCode()) );
174  pam_shutdown(); //make sure that PAM shuts down properly
175  //Now remove this user's access to the Xserver
176  QString xhostcmd = "xhost -si:localuser:"+xuser;
177  system(xhostcmd.toUtf8());
178}
179
180void XProcess::setupSessionEnvironment(){
181  // Setup any specialized environment variables
182  QProcessEnvironment environ = this->processEnvironment();
183  // Check the current locale code
184  QString langCode = xlang;
185  if( langCode.toLower() == "c" ){ langCode = "en_US"; } // default to the US english (PCDM code default), LANG=C causes problems
186  if(!environ.value("MM_CHARSET").isEmpty() ){ langCode.append( "."+environ.value("MM_CHARSET") ); }
187  else{ langCode.append(".UTF-8"); }
188  // USER, HOME, and SHELL are set by the "su" login
189  environ.insert("LOGNAME",xuser); //Login name
190  environ.insert("USERNAME",xuser); // Username
191  environ.insert("USER",xuser); // Username
192  environ.insert("PATH",environ.value("PATH")+":"+xhome+"/bin"); // Append the user's home dir to the path
193  environ.insert("LANG",langCode); //Set the proper localized language
194  environ.insert("LC_ALL",langCode); //additional localization variable for some DE's
195  environ.insert("MAIL","/var/mail/"+xuser); //Set the mail variable
196  environ.insert("GROUP",xuser); //Set the proper group id
197  environ.insert("SHLVL","0"); //Set the proper shell level
198  environ.insert("HOME",xhome); //Set the users home directory
199  environ.insert("SHELL",xshell); //Set the user's default shell
200  environ.insert("PCDM_SESSION", Backend::getNLDesktopName(xde).toUpper() ); //List the desktop environment that is being started
201  this->setProcessEnvironment(environ);
202  this->setWorkingDirectory(xhome); //set the current directory to the user's home directory
203}
204
205//Stand-alone function to check a username/password combination for validity
206void XProcess::checkPW(QString user, QString pwd){
207  xuser = Backend::getUsernameFromDisplayname(user); 
208  xpwd = pwd;
209  bool ok = pam_checkPW();
210  pam_shutdown();
211  xuser.clear();
212  xpwd.clear();
213  if(ok){ emit ValidLogin(); }
214  else{ emit InvalidLogin(); }
215}
216
217/*
218 ========== PAM FUNCTIONS ==========
219*/
220static struct pam_conv pamc = { openpam_nullconv, NULL };
221
222bool XProcess::pam_checkPW(){
223 //Requires internal "xuser" and "xpwd" variables to be set
224       
225//Convert the inputs to C character arrays for use in PAM
226  QByteArray tmp = xuser.toUtf8();
227  char* cUser = tmp.data();
228  QByteArray tmp2 = xpwd.toUtf8();
229  char* cPassword = tmp2.data();
230  //initialize variables
231  bool result = FALSE;
232  int ret;
233  //Initialize PAM
234  ret = pam_start("login", cUser, &pamc, &pamh);
235  if( ret == PAM_SUCCESS ){
236    pam_started = TRUE; //flag that pam is started
237    //Place the user-supplied password into the structure
238    ret = pam_set_item(pamh, PAM_AUTHTOK, cPassword);
239    //Set the TTY
240    //ret = pam_set_item(pamh, PAM_TTY, "pcdm-terminal");
241    //Authenticate with PAM
242    ret = pam_authenticate(pamh,0);
243    if( ret == PAM_SUCCESS ){
244      //Check for valid, unexpired account and verify access restrictions
245      ret = pam_acct_mgmt(pamh,0);
246      if( ret == PAM_SUCCESS ){ result = TRUE; }
247   
248    }else{
249      pam_logFailure(ret);
250    }
251  }
252  //return verification result
253  return result;       
254}
255
256bool XProcess::pam_startSession(){
257  //This should only be run if pam_checkPW was successful
258  int ret = pam_open_session(pamh,0);
259  bool ok = FALSE;
260  if(ret == PAM_SUCCESS){ ok = TRUE; }
261  else{ pam_logFailure(ret); }
262 
263  return ok;
264}
265
266bool XProcess::pam_stopSession(){
267  //This should only be run if pam_startSession was successful
268  int ret = pam_close_session(pamh,0);
269  bool ok = FALSE;
270  if(ret == PAM_SUCCESS){ ok = TRUE; }
271  else{ pam_logFailure(ret); }
272 
273  return ok;
274}
275
276void XProcess::pam_logFailure(int ret){
277  //Interpret a PAM error message and log it
278  Backend::log("PAM Error: " + QString::number(ret));
279  switch( ret ){
280  case PAM_ABORT:
281    Backend::log(" - PAM abort error");
282    break;
283  case PAM_AUTHINFO_UNAVAIL:
284    Backend::log(" - Authentication info unavailable");
285    break;
286  case PAM_AUTH_ERR:
287    Backend::log(" - Authentication error");
288    break;
289  case PAM_BUF_ERR:
290    Backend::log(" - Buffer error");
291    break;
292  case PAM_CONV_ERR:
293    Backend::log(" - Conversion error");
294    break;
295  case PAM_CRED_INSUFFICIENT:
296    Backend::log(" - Credentials insufficient");
297    break;
298  case PAM_MAXTRIES:
299    Backend::log(" - Maximum number of tries exceeded");
300    break;
301  case PAM_PERM_DENIED:
302    Backend::log(" - Permission denied");
303    break;
304  case PAM_SERVICE_ERR:
305    Backend::log(" - Service error");
306    break;
307  case PAM_SYMBOL_ERR:
308    Backend::log(" - Symbol error");
309    break;
310  case PAM_SYSTEM_ERR:
311    Backend::log(" - System error");
312    break;
313  case PAM_USER_UNKNOWN:
314    Backend::log(" - Unknown user");
315    break;
316  default:
317    Backend::log(" - Unrecognized authentication error");
318  }
319       
320}
321
322void XProcess::pam_shutdown(){
323  if(pam_session_open){
324    pam_stopSession();
325    pam_session_open = FALSE;
326  }
327  if(pam_started){
328    pam_end(pamh,0);
329    pam_started = FALSE;
330  }
331}
Note: See TracBrowser for help on using the repository browser.