Как заменить команду exec системной командой в php - PullRequest
0 голосов
/ 23 сентября 2011

Вот мой код для генерации сертификата PHP

Для генерации CSR

 if(isset($_POST['gencsr']))
    {   
            AddLog("sslconfig.php","gencsr",ERR_ERROR);

            /* Storing the values entered by the user for re-display in case a validation check fails */
            $_SESSION['dummycountryname']   = trim($_POST["countryname"]);
            $_SESSION['dummyprovince'] = trim($_POST["province"]);
            $_SESSION['dummylocalityname'] = trim($_POST["localityname"]);
            $_SESSION['dummyorganizationname']     = trim($_POST["organizationname"]);
            $_SESSION['dummyorganizationunit']    = trim($_POST["organizationunit"]);
            $_SESSION['dummycommonname']       = trim($_POST["commonname"]);
            $_SESSION['dummyemail']       = trim($_POST["email"]);

        if($_POST['countryname']=='')
        {
            unset ($_SESSION['dummycountryname']);
            seterror('0:|:  :|: Please enter country name.');
            header("Location: ssl.php");
            exit;
        }
        if(strlen($_POST['countryname'])!=2)
        {
            unset ($_SESSION['dummycountryname']);
            seterror('0:|:  :|: Please enter country name in two letters.');
            header("Location: ssl.php");
            exit;
        }
        if(!eregi("^[a-zA-Z]+$",$_POST['countryname'])) 
        {
            unset ($_SESSION['dummycountryname']);
            seterror('0:|:  :|: Please enter valid country name.');
            header("Location: ssl.php");
            exit;
        }

        if($_POST['province']=='')
        {
            unset ($_SESSION['dummyprovince']);
            seterror('0:|:  :|: Please enter province name.');
            header("Location: ssl.php");
            exit;
        }

        if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['province']))) 
        {
            unset ($_SESSION['dummyprovince']);
            seterror('0:|:  :|: Please enter valid province name.');
            header("Location: ssl.php");
            exit;
        }
        if($_POST['localityname']=='')
        {
            unset ($_SESSION['dummylocalityname']);
            seterror('0:|:  :|: Please enter locality name.');
            header("Location: ssl.php");
            exit;
        }
        if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['localityname']))) 
        {
            unset ($_SESSION['dummylocalityname']);
            seterror('0:|:  :|: Please enter valid locality name.');
            header("Location: ssl.php");
            exit;
        }
        if($_POST['organizationname']=='')
        {
            unset ($_SESSION['dummyorganizationname']);
            seterror('0:|:  :|: Please enter organization name.');
            header("Location: ssl.php");
            exit;
        }
        if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['organizationname']))) 
        {
            unset ($_SESSION['dummyorganizationname']);
            seterror('0:|:  :|: Please enter valid organization name.');
            header("Location: ssl.php");
            exit;
        }
        if($_POST['organizationunit']=='')
        {
            unset ($_SESSION['dummyorganizationunit']);
            seterror('0:|:  :|: Please enter organizational unit name.');
            header("Location: ssl.php");
            exit;
        }
        if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['organizationunit']))) 
        {
            unset ($_SESSION['dummyorganizationunit']);
            seterror('0:|:  :|: Please enter valid organizational unit name.');
            header("Location: ssl.php");
            exit;
        }

        if($_POST['commonname']=='')
        {
            unset ($_SESSION['dummycommonname']);
            seterror('0:|:  :|: Please enter common name.');
            header("Location: ssl.php");
            exit;
        }

        $pos = strpos($_POST['commonname'],'.');
        if($pos===false)
        {
            unset ($_SESSION['dummycommonname']);
            seterror('0:|:  :|: Please enter valid common name.');
            header("Location: ssl.php");
            exit;
        }

        $hostname = substr($_POST['commonname'],0,$pos);
        $domainname = strstr($_POST['commonname'], '.');
        $domainname = substr($domainname,1);
        AddLog("sslconfig.php",$hostname,ERR_DEBUG_HIGH);
        AddLog("sslconfig.php",$domainname,ERR_DEBUG_HIGH);
        if(!validateHostName($hostname)||$hostname=="")
        {
            unset ($_SESSION['dummycommonname']);
            seterror('0:|:  :|: Please enter valid common name.');
            $error_text="Please enter valid common name.'";
            AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
            header("Location: ssl.php");
            exit;
        }
        if(!validateDomainName($domainname))
        {
            unset ($_SESSION['dummycommonname']);
            seterror('0:|:  :|: Please enter valid common name.');
            $error_text="Please enter valid common name.'";
            AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
            header("Location: ssl.php");
            exit;
        }
        if(!validateEmail($_POST['email']))
        {
            unset ($_SESSION['dummyemail']);
            seterror('0:|:  :|: Please enter valid email address.');
            header("Location: ssl.php");
            exit;
        }

    $dn = array("C" => "".trim($_POST['countryname']),
       "ST" => "".trim($_POST['province']),
       "L" => "".trim($_POST['localityname']),
       "O" => "".trim($_POST['organizationname']),
       "OU" => "".trim($_POST['organizationunit']),
       "CN" => "".trim($_POST['commonname']),
       "emailAddress" => "".trim($_POST['email']));

        // Generate a new private (and public) key pair
        $privkey = openssl_pkey_new();
        AddLog("sslconfig.php","privkey:".$privkey,ERR_DEBUG_HIGH);

        $csr = openssl_csr_new($dn,$privkey);   
        openssl_csr_export($csr, $csrout);

        sendmail($csrout);
        AddLog("sslconfig.php","csr:".$csr,ERR_DEBUG_HIGH);
        openssl_csr_export_to_file ($csr,"/portal/data/config/certificate/CSR.crt");
        openssl_pkey_export_to_file ($privkey,"/portal/data/config/certificate/pk.key");
        unsetSessionVariables();
        header("Location: ssl.php");
        exit;
    }

и для del

// To Delete CSR
if(isset($_POST['delcsr']))
{
    if(unlink("/portal/data/config/certificate/pk.key") && unlink("/portal/data/config/certificate/CSR.crt"))
        seterror('8:|:  :|: CSR deleted successfully.');
    else
        seterror('0:|:  :|: CSR deletion failed.');
    unsetSessionVariables();
    header("Location: ssl.php");
    exit;
}

Теперь я хочу

  1. Замените команду exec системной командой в php
  2. И мой новый путь:
    Генерация запроса сертификата
    openssl req -new -nodes -out / portal /данные / конфиг / сертификат / поставщик / запросы / couffin-req.pem -keyout /portal/data/config/certificate/vendor/requests/couffin-req.key -subj "/ C = IN / ST = MAHARASHTRA / L = MUMBAI/ O = Couffin Inc / OU = Продажи / CN = www.couffin.itpl "-config /portal/data/config/certificate/vendor/openssl.cnf
    Подписание запроса на сертификат
    openssl ca -policy policy_anything -batch -out /portal/data/config/certificate/vendor/certs/couffin-cert.pem -config /portal/data/config/certificate/vendor/conf/openssl.cnf -infiles / portal /data / config / сертификат / поставщик / запросы / couffin-req.pem

Вот некоторые функции, которые я использую exec там

например

function isp7bcertificate($p7btmpfilename)
{
    $cmd = 'openssl pkcs7 -in '.$p7btmpfilename;
    exec($cmd,$array1,$error_code);
    if($error_code==0)      // p7b certificate is PEM encoded
    {
        $error_text="certificate is in PEM p7b format";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
        return true;
    }
    // // p7b certificate is DER encoded
    $cmd = 'openssl pkcs7 -inform DER -in '.$p7btmpfilename;
    exec($cmd,$array1,$error_code);
    if($error_code==0)
    {
        $error_text="certificate is in DER p7b format";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
        return true;
    }
    $error_text="certificate is not in p7b format";
    AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    return false;               // certificate not in p7b format.
}

а такжездесь

function uploadcert($certfilename,$pkfilename)
{
    $folderpath = '/portal/data/config/certificate/';
    $tmpfolderpath = '/portal/data/config/certificate/tmp/';
    $error_text="upload cert called";
    AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    if(!file_exists($tmpfolderpath.$certfilename))
    {
        $error_text="Certificate file not found.";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
        return "0:|:  :|: Certificate file not found.";
    }
    else
    {
        $error_text="Certificate file present.";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    }
    if(!file_exists($tmpfolderpath.$pkfilename))
    {
        $error_text="Private key file not found.";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
        return "0:|:  :|: Private key file not found.";
    }
    else
    {
        $error_text="Privatekey file present.";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    }

    // To fix Bug 5468 Starts
    if(!isbase64certificate($tmpfolderpath.$certfilename))
    {
        $error_text="Output : Failed to upload certificate.";
        AddLog("sslconfig.php",$error_text,ERR_ERROR);
        return "0:|: :|: Failed to upload certificate.";
    }

    //Fix for Bug 5195
    //Check if a private key corresponds to a selected certificate.
    $cert_content = file_get_contents($tmpfolderpath.$certfilename);
    $priv_key_content = file_get_contents($tmpfolderpath.$pkfilename);
    $error_text="openssl_x509_check_private_key called";
    AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    $output = openssl_x509_check_private_key($cert_content,$priv_key_content);
    $error_text="Output:".$output;
    AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    if($output)
    {
        $error_text="Output : Private Key OK";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    } 
    else 
    {
        $error_text="Output : Private Key NOT OK";
        AddLog("sslconfig.php",$error_text,ERR_ERROR);
        return "0:|: :|: Private key does not correspond to selected certificate.";
    }

    //first rename the current localhost.crt and localhost.key as old. and then copy new files.
    if (!copy($folderpath.'localhost.crt', $tmpfolderpath.'oldlocalhost.crt')) 
    {
        $error_text="error in localhost.crt copy to oldlocalhost.crt";
        AddLog("sslconfig.php",$error_text,ERR_ERROR);
        return "0:|: :|: Certificate file corrupted.";
    }
    else
    {
        $error_text="localhost.crt copied to oldlocalhost.crt";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    }
    if (!copy($folderpath.'localhost.key', $tmpfolderpath.'oldlocalhost.key')) 
    {
        //if copy of private key is failed restore the old localhost.crt
        copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
        $error_text="error in localhost.key copy to oldlocalhost.key";
        AddLog("sslconfig.php",$error_text,ERR_ERROR);
        return "0:|: :|: Private key file corrupted.";
    }
    else
    {
        $error_text="localhost.key copied to oldlocalhost.key";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
    }

    $outcert = copy($tmpfolderpath.$certfilename, $folderpath.'localhost.crt');
    $outpk = copy($tmpfolderpath.$pkfilename, $folderpath.'localhost.key');

    if((!$outcert) || (!$outpk))
    {
        copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
        copy($tmpfolderpath.'oldlocalhost.key', $folderpath.'localhost.key');
        $cmd = 'service httpd restart';
        exec($cmd,$array1,$error_code);
        $error_text="Certificate and Private key copy error";
        AddLog("sslconfig.php",$error_text,ERR_ERROR);
        return "0:|:  :|: Certificate and Private key copy error.";
    }
    $cmd = 'service httpd restart';
    exec($cmd,$array1,$error_code);
    if($error_code!=0)
    {
        //httpd fail to start. Restore to original files
        copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
        copy($tmpfolderpath.'oldlocalhost.key', $folderpath.'localhost.key');
        $cmd = 'service httpd restart';
        exec($cmd,$array1,$error_code);
        $error_text="httpd fail to restart with new files";
        AddLog("sslconfig.php",$error_text,ERR_ERROR);
        //seterror('0:|:  :|: Certificate and Private key mismatched.');
        return "0:|:  :|: Certificate and Private key mismatched.";     
    }
    else
    {
        copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
        copy($tmpfolderpath.'oldlocalhost.key', $folderpath.'localhost.key');
        $cmd = 'service httpd restart';
        exec($cmd,$array1,$error_code);
        $error_text="httpd restart successful with new files";
        AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
        return "success";
    }

}

1 Ответ

0 голосов
/ 23 сентября 2011

это может быть очень короткий ответ, но я не знаю, что еще следует сказать:

, поскольку в вашем коде нет exec -команд, заменять нечего.вывод: это уже сделано.

для замены exec / system в общем, это просто небольшое изменение в коде:

exec($command,$return,$error);

просто получает

$return = system($command,$error);

для получения дополнительной информации прочитайте документацию для exec () и для system ()

...