Code

Fixed sudo filter scope
[gosa.git] / gosa-plugins / sudo / admin / sudo / class_sudoGeneric.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id: class_sudo.inc 9975 2008-03-25 14:09:30Z hickert $$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
24 /*! \brief Sudo generic class. Allow setting User/Host/Command/Runas
25            for a sudo role object.
26  */
27 class sudo extends plugin
28 {
30   protected $cn= "";
31   protected $description= "";
33   protected $sudoUser   = array("ALL");
34   protected $sudoCommand= array();
35   protected $sudoHost   = array("ALL");
36   protected $sudoRunAs  = array("ALL");
37   protected $accessTo         = array();
38   protected $trustModel       = "";
40   private $is_default = FALSE;
41   private $was_trust_account= FALSE;
43   public $objectclasses = array("top","sudoRole");
44   public $attributes    = array("cn","description","sudoUser","sudoCommand","sudoHost","sudoRunAs","accessTo","trustModel");
46   public $ignore_account = TRUE;
48   public $orig_dn;
50   protected $trustSelect;
52   /*! \brief  Returns to the base department for sudo roles.
53               This department is then used to store new roles.
54       @param  Object  GOsa configuration object.
55       @return String sudo store department
56    */
57   public static function get_sudoers_ou($config)
58   {
59     return(get_ou("sudoRDN").$config->current['BASE']);
60   }
62   /*! \brief  Initializes this sudo class, with all required attributes.
63       @param  Object $config  GOsa configuration object.
64       @param  String $db      "new" or the sudo role dn.
65       @return .
66    */
67   function sudo(&$config, $dn= NULL)
68   {
69     plugin::plugin ($config, $dn);
71     if($this->initially_was_account){
72       foreach(array("sudoUser","sudoCommand","sudoHost","sudoRunAs") as $attr){
73         $this->$attr = array();
74         if(isset($this->attrs[$attr])){
75           $tmp = array();
76           for($i = 0 ; $i < $this->attrs[$attr]['count']; $i++){
77             $tmp[] = $this->attrs[$attr][$i];
78           }
79           $this->$attr = $tmp;
80         }
81       }
83       /* Is this account a trustAccount? */
84       if (isset($this->attrs['trustModel'])){
85         $this->trustModel= $this->attrs['trustModel'][0];
86         $this->was_trust_account= TRUE;
87       } else {
88         $this->was_trust_account= FALSE;
89         $this->trustModel= "";
90       }
92       $this->accessTo = array();
93       if (isset($this->attrs['accessTo'])){
94         for ($i= 0; $i<$this->attrs['accessTo']['count']; $i++){
95           $tmp= $this->attrs['accessTo'][$i];
96           $this->accessTo[$tmp]= $tmp;
97         }
98       }
100     }
102     if(preg_match("/^defaults$/i",$this->cn)){
103       $this->is_default = TRUE;
104     }
106     /* Get global filter config */
107     if (!session::is_set("sysfilter")){
108       $ui= get_userinfo();
109       $base= get_base_from_people($ui->dn);
110       $sysfilter= array( "depselect"       => $base,
111           "regex"           => "*");
112       session::set("sysfilter", $sysfilter);
113     }
115     $this->orig_dn = $this->dn;
116   }
119   /*! \brief  Creates the sudo generic ui. 
120       @return String  The generated HTML content for this plugin. 
121    */
122   function execute()
123   {
124     /* Call parent execute */
125     plugin::execute();
127     /*********************
128        Access control list / trust mode 
129      *********************/ 
131     /* Add user workstation? */
132     if (isset($_POST["add_ws"])){
133       $this->trustSelect= new trustSelect($this->config,get_userinfo());
134       $this->dialog= TRUE;
135     }
137     // Add selected machines to trusted ones.
138     if (isset($_POST["add_ws_finish"]) &&  $this->trustSelect){
139       $trusts = $this->trustSelect->detectPostActions();
140       if(isset($trusts['targets'])){
142         $headpage = $this->trustSelect->getHeadpage();
143         foreach($trusts['targets'] as $id){
144           $attrs = $headpage->getEntry($id);
145           $this->accessTo[$attrs['cn'][0]]= $attrs['cn'][0];
146         }
147         ksort($this->accessTo);
148         $this->is_modified= TRUE;
149       }
150       $this->trustSelect= NULL;
151       $this->dialog= FALSE;
152     }
155     /* Remove user workstations? */
156     if (isset($_POST["delete_ws"]) && isset($_POST['workstation_list'])){
157       foreach($_POST['workstation_list'] as $name){
158         unset ($this->accessTo[$name]);
159       }
160       $this->is_modified= TRUE;
161     }
163     /* Add user workstation finished? */
164     if (isset($_POST["add_ws_finish"]) || isset($_POST["add_ws_cancel"])){
165       $this->trustSelect= NULL;
166       $this->dialog= FALSE;
167     }
169     /* Show ws dialog */
170     if ($this->trustSelect){
172       // Build up blocklist
173       session::set('filterBlacklist', array('cn' => array_values($this->accessTo)));
174       return($this->trustSelect->execute());
175     }
178     /*********************
179        Add users 
180      *********************/ 
181  
182     if(isset($_POST['list_sudoUser']) && !is_object($this->dialog) && $this->acl_is_writeable("sudoUser")){
183       $this->dialog =new userGroupSelect($this->config,get_userinfo());
184     }
185    
186     /* Add selected hosts  to the sudoUser list */ 
187     if(isset($_POST['userGroupSelect_save']) && $this->dialog instanceof userGroupSelect){
188       if($this->acl_is_writeable("sudoUser")){
189         foreach($this->dialog->save() as $entry){
190           if(in_array("posixGroup",$entry['objectClass'])){
191             $name = trim("%".$entry['cn'][0]);
192           }elseif(isset($entry['uid'][0])){
193             $name = trim($entry['uid'][0]);
194           }
195           if(!in_array($name,$this->sudoUser) && !in_array("!".$name,$this->sudoUser)){
196             $this->sudoUser[] = $name;
197           }
198         }   
199       }
200       unset($this->dialog);
201       $this->dialog = NULL;
202     }    
204     if(isset($_POST['userGroupSelect_cancel']) && $this->dialog instanceOf userGroupSelect){
205       unset($this->dialog);
206       $this->dialog = NULL;
207     }    
209     if($this->dialog instanceOf userGroupSelect){
210       $used = array();
211       foreach($this->sudoUser as $name){
212         $str = preg_replace("/^!/","",$name);
213         if(preg_match("/^%/", $str)){
214           $used['cn'][] = preg_replace("/^%/","",$str);
215         }else{
216           $used['uid'][] = $str;
217         }
218       }
220       // Build up blocklist
221       session::set('filterBlacklist', $used);
222       return($this->dialog->execute());
223     }
224  
227     /*********************
228        Add systems 
229      *********************/ 
230   
231     if(isset($_POST['list_sudoHost']) && !is_object($this->dialog) && $this->acl_is_writeable("sudoHost")){
232       $this->dialog =new systemSelect($this->config,get_userinfo());
233     }
234    
235     /* Add selected hosts  to the sudoHost list */ 
236     if(isset($_POST['systemSelect_save']) && $this->dialog instanceof systemSelect){
237       if($this->acl_is_writeable("sudoHost")){
238         foreach($this->dialog->save() as $entry){
239           $cn = trim($entry['cn'][0]);
240           if(!in_array($cn,$this->sudoHost) && !in_array("!".$cn,$this->sudoHost)){
241             $this->sudoHost[] = $cn;
242           }
243         }   
244       }   
245       unset($this->dialog);
246       $this->dialog = NULL;
247     }    
249     if(isset($_POST['systemSelect_cancel']) && $this->dialog instanceOf systemSelect){
250       unset($this->dialog);
251       $this->dialog = NULL;
252     }    
254     if($this->dialog instanceOf systemSelect){
255       $used = array();
256       foreach($this->sudoHost as $name){
257         $used['cn'][] = preg_replace("/^!/","",$name);
258       }
260       // Build up blocklist
261       session::set('filterBlacklist', $used);
262       return($this->dialog->execute());
263     }
264   
265     /*********************
266        Dialog handling / display / close  
267      *********************/ 
268   
269     if(is_object($this->dialog)){
270       return($this->dialog->execute());
271     }
273  
274     /*********************
275        NEGATE values 
276      *********************/ 
277     foreach($_POST as $name => $value){
278       if(preg_match("/^neg_/",$name)){
279         $attr = preg_replace("/^neg_([^_]*)_.*$/","\\1",$name);
280         $value= preg_replace("/^neg_[^_]*_([0-9]*)_.*$/","\\1",$name);
281  
282         if($this->acl_is_writeable($attr)){
283           $attrs = $this->$attr;
284           if(isset( $attrs[$value])){
285             $v =  $attrs[$value];
286             if(preg_match("/^!/",$v)){
287               $attrs[$value] = preg_replace("/^!/","",$v);
288             }else{
289               $attrs[$value] = "!".$v;
290             }
291             $this->$attr = $attrs;  
292           }
293         }
294         break; // Do it once, image inputs will be posted twice
295       }
296     }
297   
298     /*********************
299        Delete values 
300      *********************/ 
301     foreach($_POST as $name => $value){
302       if(preg_match("/^del_/",$name)){
303         $attr = preg_replace("/^del_([^_]*)_.*$/","\\1",$name);
304         $value= preg_replace("/^del_[^_]*_([0-9]*)_.*$/","\\1",$name);
305         if($this->acl_is_writeable($attr)){
306           $attrs = $this->$attr;
307           if(isset( $attrs[$value])){
308             unset($attrs[$value]);
309             $this->$attr = $attrs;  
310           }
311         }
312         break; // Do it once, image inputs will be posted twice
313       }
314     }
317     /*********************
318        ADD values 
319      *********************/
321     /* User / Host / Runas */ 
322     foreach(array("sudoUser","sudoHost","sudoRunAs") as $attr){
323       if($this->acl_is_writeable($attr) && 
324           isset($_POST["add_".$attr]) && 
325           isset($_POST['new_'.$attr]) && 
326           !empty($_POST['new_'.$attr])){
327         if(preg_match("/^[a-z\.0-9]*$/i",$_POST['new_'.$attr])){
328           $attrs = $this->$attr;
329           $attrs[] =  trim($_POST['new_'.$attr]); 
330           $this->$attr = $attrs;
331         }else{
332           msg_dialog::display(_("Error"),msgPool::invalid($attr,$_POST['new_'.$attr],"/[a-z0-9]/"));
333         }
334       }
335     }
337     /* Command */
338     foreach(array("sudoCommand") as $attr){
339       if($this->acl_is_writeable($attr) && isset($_POST["add_".$attr]) && isset($_POST['new_'.$attr])){
340         $attrs = $this->$attr;
341         $attrs[] =  trim($_POST['new_'.$attr]); 
342         $this->$attr = $attrs;
343       }
344     }
346     
347     /*********************
348        SMARTY assignments 
349      *********************/
351     $smarty = get_smarty();
352     $smarty->assign("is_default",$this->is_default);
353     foreach($this->attributes as $attr){
354       if(is_string($this->$attr)){
355         $smarty->assign($attr,htmlentities($this->$attr));
356       }else{
357         $smarty->assign($attr,$this->$attr);
358       }
359       $smarty->assign($attr."ACL",$this->getacl($attr));
360     }
362     /* Work on trust modes */
363     $smarty->assign("trusthide", " disabled ");
364     if ($this->trustModel == "fullaccess"){
365       $trustmode= 1;
366     } elseif ($this->trustModel == "byhost"){
367       $trustmode= 2;
368       $smarty->assign("trusthide", "");
369     } else {
370       $trustmode= 0;
371     }
372     $smarty->assign("trustmode", $trustmode);
373     $smarty->assign("trustmodes", array( 
374           0 => _("disabled"), 
375           1 => _("full access"),
376           2 => _("allow access to these hosts")));
378     if((count($this->accessTo))==0){
379       $smarty->assign("emptyArrAccess",true);
380     }else{
381       $smarty->assign("emptyArrAccess",false);
382     }
383     $smarty->assign("workstations", $this->accessTo);
384     
385     /* Create lists 
386      */
387     $divlist_sudoUser = new divSelectBox("divlist_sudoUser");
388     $divlist_sudoUser->SetHeight("90");
389     $divlist_sudoHost = new divSelectBox("divlist_sudoHost");
390     $divlist_sudoHost->Setheight("90");
391     $divlist_sudoRunAs = new divSelectBox("divlist_sudoRunAs");
392     $divlist_sudoRunAs->Setheight("90");
393     $divlist_sudoCommand = new divSelectBox("divlist_sudoCommand");
394     $divlist_sudoCommand->Setheight("90");
396     /* Fill divlists
397      */
398     $neg_img= "<img src='plugins/sudo/images/negate.png' alt='!' class='center'>"; 
399     $option = "<input type='image' src='plugins/sudo/images/negate.png'     name='neg_%ATTR%_%KEY%' class='center'>"; 
400     $option.= "<input type='image' src='images/lists/trash.png'  name='del_%ATTR%_%KEY%' class='center'>"; 
401     foreach(array("sudoCommand","sudoHost","sudoRunAs") as $attr){
402       if($this->acl_is_readable($attr)){
403         foreach($this->$attr as $key => $entry){
404           $neg = "";
405           if(preg_match("/^!/",$entry)){
406             $neg = $neg_img;
407           }
408           $entry = preg_replace("/^!/","",$entry);
409           $list_name = "divlist_".$attr;
410           $$list_name->AddEntry(
411               array(
412                 array("string" => $neg,"attach" => "style='width:18px;'"),
413                 array("string" => $entry),
414                 array("string" => preg_replace(array("/%KEY%/","/%ATTR%/"),array($key,$attr),$option),
415                   "attach" => "style='width:40px; border-right: 0px;'")));
416         }
417       }
418     }
420     foreach(array("sudoUser") as $attr){
421       $img1 = "<img src='plugins/users/images/select_user.png'   alt='"._("User")."' class='center'>";
422       $img2 = "<img src='plugins/groups/images/groups.png' alt='"._("Group")."' class='center'>";
423       if($this->acl_is_readable($attr)){
424         foreach($this->$attr as $key => $entry){
425           $neg = "";
426           if(preg_match("/^!/",$entry)){
427             $neg = $neg_img;
428           }
429           $entry = preg_replace("/^!/","",$entry);
431           $img = $img1;
432           if(preg_match("/^%/",$entry)){
433             $img = $img2;
434           }
435           $entry = preg_replace("/^%/","",$entry);
436   
437           $list_name = "divlist_".$attr;
438           $$list_name->AddEntry(
439               array(
440                 array("string" => $neg,"attach" => "style='width:18px;'"),
441                 array("string" => $img,"attach" => "style='width:18px;'"),
442                 array("string" => $entry),
443                 array("string" => preg_replace(array("/%KEY%/","/%ATTR%/"),array($key,$attr),$option),
444                   "attach" => "style='width:40px; border-right: 0px;'")));
445         }
446       }
447     }
452     /* Tell smarty about our divlists 
453      */
454     $smarty->assign("divlist_sudoUser",   $divlist_sudoUser->DrawList());
455     $smarty->assign("divlist_sudoHost",   $divlist_sudoHost->DrawList());
456     $smarty->assign("divlist_sudoRunAs",  $divlist_sudoRunAs->DrawList());
457     $smarty->assign("divlist_sudoCommand",$divlist_sudoCommand->DrawList());
458     return($smarty->fetch(get_template_path('generic.tpl', TRUE)));
459   }
462   /*! \brief  Remove this sudo role from the ldap server 
463    */
464   function remove_from_parent()
465   {
466     plugin::remove_from_parent();
468     $ldap = $this->config->get_ldap_link();
469     $ldap->cd($this->dn);
470     $ldap->rmdir($this->dn);
472     /* Send signal to the world that we've done */
473     $this->handle_post_events("remove");
474   }
477   /*! \brief  Save all relevant HTML posts. 
478    */
479   function save_object()
480   {
481     plugin::save_object();
482     
483     if($this->is_default){
484       $this->cn = "defaults";
485     }  
487     /* Trust mode - special handling */
488     if($this->acl_is_writeable("trustModel")){
489       if (isset($_POST['trustmode'])){
490         $saved= $this->trustModel;
491         if ($_POST['trustmode'] == "1"){
492           $this->trustModel= "fullaccess";
493         } elseif ($_POST['trustmode'] == "2"){
494           $this->trustModel= "byhost";
495         } else {
496           $this->trustModel= "";
497         }
498         if ($this->trustModel != $saved){
499           $this->is_modified= TRUE;
500         }
501       }
502     }
503   }
506   /*! \brief  Save changes into the ldap database.
507    */
508   function save()
509   {
510     plugin::save();
511    /* Trust accounts */
512     $objectclasses= array();
513     foreach ($this->attrs['objectClass'] as $key => $class){
514       if (preg_match('/trustAccount/i', $class)){
515         continue;
516       }
517       $objectclasses[]= $this->attrs['objectClass'][$key];
518     }
520     $this->attrs['objectClass']= $objectclasses;
521     if ($this->trustModel != ""){
522       $this->attrs['objectClass'][]= "trustAccount";
523       $this->attrs['trustModel']= $this->trustModel;
524       $this->attrs['accessTo']= array();
525       if ($this->trustModel == "byhost"){
526         foreach ($this->accessTo as $host){
527           $this->attrs['accessTo'][]= $host;
528         }
529       }
530     } else {
531       if ($this->was_trust_account){
532         $this->attrs['accessTo']= array();
533         $this->attrs['trustModel']= array();
534       }
535     }
538     /* Ensure a correct array index 
539      */ 
540     $this->attrs['sudoHost']    = array_values($this->attrs['sudoHost']);
541     $this->attrs['sudoRunAs']   = array_values($this->attrs['sudoRunAs']);
542     $this->attrs['sudoUser']    = array_values($this->attrs['sudoUser']);
543     $this->attrs['sudoCommand'] = array_values($this->attrs['sudoCommand']);
545     $this->cleanup();
547     $ldap = $this->config->get_ldap_link();
548     $ldap->cd($this->config->current['BASE']);
550     if($this->is_new){
551       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
552       $ldap->cd($this->dn);
553       $ldap->add($this->attrs);
555       /* Send signal to the world that we've done */
556       $this->handle_post_events("create");
557     }else{
558       $ldap->cd($this->dn);
559       $ldap->modify($this->attrs);;
561       /* Send signal to the world that we've done */
562       $this->handle_post_events("modify");
563     }
565     if (!$ldap->success()){
566       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
567     }
568   }
571   /*! \brief  Check the given input.
572       @return Array   All error messages in an array();
573    */
574   function check()
575   {
576     $message = plugin::check();
578     /* Is a name given? */
579     if($this->cn == ""){
580       $message[] = msgPool::required(_("Name"));
581     }
583     /* Check if name is reserved */
584     if(!$this->is_default && preg_match("/^defaults$/i",$this->cn)){
585       $message[] = msgPool::reserved(_("Name"));
586     }
588     /* Check name */
589     if(!preg_match("/^[0-9a-z\@]*$/i",$this->cn)){
590       $message[] = msgPool::invalid(_("Name"),$this->cn,"/[0-9a-z\@]/i");
591     }
593     /* Check if this entry will cause duplicated ldap entries */
594     $ldap = $this->config->get_ldap_link();
595     $ldap->cd($this->get_sudoers_ou($this->config));
596     $ldap->search("(&(objectClass=sudoRole)(cn=".$this->cn."))");
597     while($attrs = $ldap->fetch()){
598       if($attrs['dn'] != $this->dn){
599         $message[] = msgPool::duplicated(_("Name"));
600       }
601     }
603     /* Check if we are allowed to create or move this object
604      */
605     if($this->orig_dn == "new" && !$this->acl_is_createable($this->get_sudoers_ou($this->config))){
606       $message[] = msgPool::permCreate();
607     }
609     return ($message);
610   }
613   /*! \brief Force this entry to be handled and saved as 'default'
614       @param  BOOL  TRUE -force defaults   FALSE -normal
615    */
616   public function set_default($state)
617   {
618     $this->is_default = TRUE;
619     $this->cn = "defaults";
620   }
623   /*! \brief  Add ACL object
624       @return Returns the ACL object.
625    */
626   static function plInfo()
627   {
628     return (array(  
629           "plShortName" => _("Sudo"),
630           "plDescription" => _("Sudo role"),
631           "plSelfModify"  => FALSE,
632           "plDepends"     => array(),
633           "plPriority"    => 0,
634           "plSection"     => array("administration"),
635           "plCategory"    => array("sudo" => array("objectClass" => "sudoRole", "description" => _("Sudo role"))),
637           "plProvidedAcls"    => array(
638             "cn"                => _("Name"),
639             "description"       => _("Description"),
640             "sudoUser"          => _("Users"),
641             "sudoHost"          => _("Host"),
642             "sudoCommand"       => _("Command"),
643             "sudoRunAs"         => _("Run as user"),
644             "trustModel"        => _("Access control list"))
645         ));
646   }
649   /*! \brief  This function will be called if an object gets copied.
650               This function adapts attributes from the source object.
651       @param  Array The source object.
652    */
653   function PrepareForCopyPaste($source)
654   {
655     plugin::PrepareForCopyPaste($source);
656     foreach(array("sudoUser","sudoCommand","sudoHost","sudoRunAs") as $attr){
657       $this->$attr = array();
658       if(isset($source[$attr])){
659         $tmp = array();
660         for($i = 0 ; $i < $source[$attr]['count']; $i++){
661           $tmp[] = $source[$attr][$i];
662         }
663         $this->$attr = $tmp;
664       }
665     }
667     /* Is this account a trustAccount? */
668     if (isset($source['trustModel'])){
669       $this->trustModel= $source['trustModel'][0];
670       $this->was_trust_account= TRUE;
671     } else {
672       $this->was_trust_account= FALSE;
673       $this->trustModel= "";
674     }
676     $this->accessTo = array();
677     if (isset($source['accessTo'])){
678       for ($i= 0; $i<$source['accessTo']['count']; $i++){
679         $tmp= $source['accessTo'][$i];
680         $this->accessTo[$tmp]= $tmp;
681       }
682     }
683   }
686   /*! \brief  Used for copy & paste.
687               Returns a HTML input mask, which allows to change the cn of this entry.
688       @param  Array   Array containing current status && a HTML template.              
689    */
690   function getCopyDialog()
691   {
692     $vars = array("cn");
693     $smarty = get_smarty();
694     $smarty->assign("cn", htmlentities($this->cn));
695     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE));
696     $ret = array();
697     $ret['string'] = $str;
698     $ret['status'] = "";
699     return($ret);
700   }
703   public function get_cn()
704   {
705     return($this->cn);
706   }
709   /*! \brief  Used for copy & paste.
710               Some entries must be renamed to avaoid duplicate entries.
711    */
712   function saveCopyDialog()
713   {
714     if(isset($_POST['cn'])){
715       $this->cn = get_post('cn');
716     }
717   }
719 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
720 ?>