Simple PHP encrypt and decrypt

You need to have openssl encrypt installed and running. Check this thread if you dont have it already
http://stackoverflow.com/questions/11525524/why-cant-i-use-openssl-encrypt

/**
 * simple method to encrypt or decrypt a plain text string
 * initialization vector(IV) has to be the same when encrypting and decrypting
 * PHP 5.4.9 ( check your PHP version for function definition changes )
 *
 * this is a beginners template for simple encryption decryption
 * before using this in production environments, please read about encryption
 * use at your own risk
 *
 * @param string $action: can be 'encrypt' or 'decrypt'
 * @param string $string: string to encrypt or decrypt
 *
 * @return string
 */
function encrypt_decrypt($action, $string) {
    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = 'This is my secret key';
    $secret_iv = 'This is my secret iv';

    // hash
    $key = hash('sha256', $secret_key);
    
    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    if( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    }
    else if( $action == 'decrypt' ){
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}

$plain_txt = "This is my plain text";
echo "Plain Text = $plain_txt\n";

$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = $encrypted_txt\n";

$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text = $decrypted_txt\n";

if( $plain_txt === $decrypted_txt ) echo "SUCCESS";
else echo "FAILED";

echo "\n";

Putting today’s date on the form using javascript

Use the following code to put the date in the form.

<input type="text" id="todaydate" size="15" ></font></p>
 <script type="text/javascript" >
  var today = new Date();
 var dd = today.getDate();
 var mm = today.getMonth()+1; //January is 0!
 var yyyy = today.getFullYear();
if(dd<10) {
 dd='0'+dd
 }
if(mm<10) {
 mm='0'+mm
 } 
 today = yyyy+'-'+mm+'-'+dd;
 var element = document.getElementById("todaydate");
 element.value = today;
 </script>

 

How to create bulk contact list from CSV file.

1. From the Source Exchange Server, create the CSV file. Go to the source Exchange Management Console, and navigate to Recipient Configuration and Mailbox. Right click on the Mailbox and choose View and Add/Remove Columns. From the list of columns that is available, choose all the columns that you may think you need. csv1

2. Go to the source Exchange Management Console, and navigate to Recipient Configuration and Mailbox. Right click on the Mailbox and Select Export List option.

Exchange1

3. Make sure to choose Text (Comma Delimited) (*.csv) option from from the Save as type drop down box. Save the file on the drive.

exchange2

4. Open the created text file using the notepad. Change headings section, so the headings do not contain any spaces.  So, “Display Name” becomes “DisplayName” and “Primary SMTP Address” becomes “PrimarySMTPAddress” and so on. Do this only on the heading, not on the content of the list.

Exchange3

5. Send the File to the destination Exchange Server and save it on the destination server. (In the example below, we will use the path c:\temp\Email.csv)

6. Open the Exchange Management Shell, and run the following script from the destination server.

The first script is used to create the contacts.

Import-Csv c:\temp\Email.csv | ForEach-Object {New-MailContact -Name $_.DisplayName -ExternalEmailAddress $_.PrimarySMTPAddress -Alias $_.Alias}

Run the script to populate the contacts with other details such as phone number, departments, position title etc.

Import-Csv c:\temp\Email.csv | ForEach-Object {   set-contact -identity $_.DisplayName -city $_.City -Company $_.Company -Department $_.Department -FirstName $_.FirstName -LastName $_.LastName  -Phone $_.Phone -StateorProvince $_.stateorprovince -Title $_.title}

HTML script that displays more text when you click more button

Simple script that you can use to put more button at the end of the paragraph. When you click on the more button, hidden texts are displayed.

<html>
<head></head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $("p_button1").click(function(){
    $("ptag1").toggle(200);
  });
  $("p_button2").click(function(){
    $("ptag2").toggle(200);
  });
});
</script>
<p >Lorem ipsum dolor sit amet, eos ex phaedrum principes. Ut nisl graeci consectetuer eum, ius ex novum maluisset. Habeo appellantur instructior duo ex, munere imperdiet te pro. Alia eleifend nam at. 
<p_button1><b>More...</b></p_button1></p>
<ptag1 style="display:none">
<p >'Ipsum luptatum cum te, idque partiendo consulatu mel no. Nulla dolorum cu mel, eum mollis bonorum cu. Eum id tibique adipiscing eloquentiam, per solet nonumy periculis id, vis simul quidam habemus eu. Ex recteque eloquentiam complectitur vix, nisl facilisi vel et. No est ocurreret splendide, has ferri voluptatibus et, duo ex consequat vituperatoribus. </p>
<p >Ea error antiopam eam. His liber nominavi appareat ad. Mea ea facilis appetere persequeris, eam purto liber zril ex. Te mea hendrerit deterruisset.</p>
</ptag1>
<p>Ne volutpat qualisque est, error appellantur cum eu, at quo aliquid laoreet. Tota doctus aliquam an pro, wisi aliquando in vis. Solet animal eos ne, mea eu odio decore. An quo elit idque maiorum. His omnium maiorum singulis ei, pri in novum munere definiebas. An nisl nostrum convenire eam, postea mnesarchum vis eu, his an facer postea. Apeirian praesent adolescens no qui. <p_button2><b>More...</b></p_button2></p>
<ptag2 style="display:none">
<p >Melius accommodare sea ut. Adhuc concludaturque sit et, has quot oratio no. An sint appareat has. Cetero suscipit cotidieque vim ei. Eros mazim quando cu eam.</p>
</ptag2>
</body></html>

 

Installing SSL Cert for cPanel/WHM Itself

Problem:

I am attempting to install a proper cert for WHM and cPanel. I ordered a cert in the name of server.mydomain.com and plunked it into WHM. However, browsers are still coming up with the original self-signed cert that WHM generates upon install.

I notice that if I go to https://server.mydomain.com there are no warnings and the cert behaves as expected. However, as soon as I try to go to https://server.mydomain.com:2087 orhttps://server.mydomain.com/whm, the self-signed certificate warning shows up again.

I assume from this that WHM is running on a different instance of Apache than my accounts. Is this true? And if so, how do I go about installing a certificate for WHM itself?

Solution:

How to Setup WHM and CPANL so clients will be redirected to a valid SSL Certificate when logging in.

Instructions based on WHM v11.15.0

1) Purchase / Install the Certificate for your fully qualified domain (ie: server.domain.com)

SSL / TLS >> Install a SSL Certificate and Setup the Domain

2) Test your new CERT

https://server.domain.com/
should resolve and the cert should function properly before moving forward.

https://server.domain.com:2087/
should be giving you an invalid certificate error

3) Install the CERT for the WHM and CPANEL Service (this is the step you don’t think about!!)

Service Configuration >> Manage Service SSL Certificates
> Select “Install New Certificate” for the “cPanel/WHM/Webmail Service”
> Select Domain this CRT is for “Browse”
> Pick the full server cert you installed “server.domain.com”
> Press “Submit” to install

4) Test your Service Certificate

https://server.domain.com:2087/
should now be working !! WHOOOO

** Once your done, you may choose to install the same cert for your SMTP, POP, and FTP accounts so that the option is available and functioning properly

NOTE: You may need to reboot the server to see changes.

Creating mediawiki for private use

Restrict account creation

To restrict account creation, you need to edit LocalSettings.php in the root path of your MediaWiki installation.

# Prevent new user registrations except by sysops
 $wgGroupPermissions['*']['createaccount'] = false;

Note Note: You can use the ConfirmAccount extension if you want to set up an account confirmation queue. (If not you may still proceed as follows.)

Note Note: New users will still be able to be created by sysops, in the following manner:

Go to [[Special:Userlogin]], when logged in as a sysop.
Click on “Create an account” link to get to the account creation form.
Enter a username and an email address, and click the “by email” button. Note you need $wgEnableEmail=true or else the sysop must pick a password and send it to the user.
The account will be created with a random password which is then emailed to the given address (as with the “forgot password” feature). The user will be requested to change password at first login; when he does this, his e-mail address will also be marked as confirmed.

When you click the “create account” button instead, you have to manually send the user his password. If you’ve set $wgMinimalPasswordLength=0 (default configuration up to version 1.15) and you’ve left the password field blank, the user will be emailed an e-mail address confirmation request but will be unable to access Special:Confirmemail to perform the confirmation. Instead, he’ll get an error (unless you’ve added it to $wgWhitelistRead); he’ll be able to login with a blank password and then confirm email, but his password will not have been reset (he’ll have to reset it manually).

It may be appropriate to edit the text displayed when a non-user attempts to log in. This can be done at [[MediaWiki:Nosuchuser]], when logged in as a sysop. Use plain text without any special formatting, as the formatting is ignored and the text is literally rendered.

Restrict editing of all pages

Users will still be able to read pages with these modifications, and they can view the source by using Special:Export/Article name or other methods (see also bug 1859).

See Help:User rights and Manual:$wgGroupPermissions. Some examples of how to protect all pages from editing (not reading) by certain classes of users:
[edit]

Restrict anonymous editing

$wgGroupPermissions['*']['edit'] = false;

Note: You may then also want to hide user tools for anonymous (IP) visitors: $wgShowIPinHeader = false;

Restrict editing by all non-sysop users

$wgGroupPermissions['*']['edit'] = false;
 $wgGroupPermissions['user']['edit'] = false;
 $wgGroupPermissions['sysop']['edit'] = true;

Restrict editing by absolutely everyone

$wgGroupPermissions['*']['edit'] = false;
 $wgGroupPermissions['user']['edit'] = false;
 $wgGroupPermissions['sysop']['edit'] = false;

Creating Secure File Upload/Download sites using UBUNTU Server

Use the following guide to create a secure file transfer site.

1. Install Ubuntu Server with SSH and LAMP enabled. Be sure to encrypt the whole hard drive.

2. (Optional) Install SFTP so users can use SFTP to transfer files.

3. Configure a Apache2 web server with SSH.

4. Edit php.ini file (/etc/php5/apache2) to increase the file upload maximum.

    1. upload_max_filesize – The maximum size of an uploaded file.
    2. post_max_size – Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size.

5. Install phpmyadmin by typing sudo apt-get phpmyadmin.

6. Under /var/www folder create a folder called “files”. Give user permission to be able to write to the folder (chmod 777 files). Create index.html in the files folder. Index.html does not need to have anything particular. Just have some text in it.

7. Modify /etc/crontab file. Add the following line at the end of the crontab file. It will delete any file older than 7 days in the /var/www/files folder, but will not delete the index.html in the folder.

1 20 * * * root touch /var/www/files/index.html
1 21 * * * root find /var/www/files/ -mtime +7 -exec rm {} \;

8. Create a database using mysql.  Use the following SQL command to create a database. Grant user access to the database.

-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Dec 08, 2015 at 03:26 PM
-- Server version: 5.5.46-0ubuntu0.14.04.2
-- PHP Version: 5.5.9-1ubuntu4.14

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `FileUploader`
--

-- --------------------------------------------------------

--
-- Table structure for table `DownloadHistory`
--

CREATE TABLE IF NOT EXISTS `DownloadHistory` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `Date` text NOT NULL,
 `IPAddress` text NOT NULL,
 `FileName` text NOT NULL,
 PRIMARY KEY (`ID`),
 UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `FileLists`
--

CREATE TABLE IF NOT EXISTS `FileLists` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `FileCode` text NOT NULL,
 `FileName` text NOT NULL,
 `Expiration` text NOT NULL,
 `FileDate` text NOT NULL,
 `CryptFileName` text NOT NULL,
 PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

9. Place the following files in the /var/www folder.

custom.php   (for $c_userid and$c_password variable, use the echo crypt(“string value”,’xx’) to generate the value)

 
<?php
$c_userid = "xxGeneratedValue"; # Upload UserID
$c_password = "xxGeneratedValue"; # Upload Password
$forbidden_file_extension = array("php","html","htm");
$dbase_name = "FileUploader"; # mysql Database Name
$dbase_user = "FileUpload"; # mysql UserID
$dbase_pass = "password"; # mysql Password
?>

download.php

<?php

function Display_Upload()
 {
$HTMLDOCS = <<<HTML1
<html>
<body>
<form action="download.php" method="post"
enctype="multipart/form-data">
<h1><center>Secure File Download</center></h1>
<table align="center">
<tr><td>File Code: </td>
<td><input type="text" name="FileCode"> </td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Download File"
/></td></tr>
</table>
</form>
</body>
</html>
HTML1;
print $HTMLDOCS;
}

function Check_Files($FileCode)
 {
 $FileCode = substr($FileCode,0,9);
if (preg_match ('/[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]/',$FileCode)==false)
 {
 echo "Wrong Code Entered. File Code is 9 digit number.";
exit;
 }
 include("custom.php");
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $sql = "select * from FileLists where FileCode = ".$FileCode;
 $result = mysql_query($sql);
 $row=mysql_fetch_array($result);
 if (mysql_num_rows($result)==0)
 {
 echo "Wrong Code Entered. Please go back and enter the correct File Code.";
 exit;
 }
 if (!file_exists("files/".$row['CryptFileName']))
 {
 echo "The requested file has expired. The file you requested is not available for download anymore.";
 exit;
 }
 }

function Write_Log($FileCode)
 {
 include ("custom.php");
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $sql = "select * from FileLists where FileCode = ".$FileCode;
 $result = mysql_query($sql);
 $row=mysql_fetch_array($result);
 $FileDate = date ("Y-m-d H:i:s");
 $FileName =$row['FileName'];
 $IPAddress = $_SERVER['REMOTE_ADDR'];
 $sql = "INSERT INTO DownloadHistory (Date,IPAddress,FileName) VALUES('";
 $sql = $sql . $FileDate."','".$IPAddress."','".$FileName."')";
 $result = mysql_query($sql);
 }

function Download_File($FileCode)
 {
 include ("custom.php");
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $sql = "select * from FileLists where FileCode = ".$FileCode;
 $result = mysql_query($sql);
 while ($row=mysql_fetch_array($result))
 {
// Headers to send your file
 header("Content-Type: application/jpeg");
 header("Content-Disposition: attachment; filename = ". $row['FileName']);
 readfile("files/".$row['CryptFileName']);
 exit;
 }
 }

// Main Program
include ("custom.php");
$success =0;
if (!isset($_POST["FileCode"]))
 {
 Display_Upload();
 } else
 {
 Check_Files($_POST["FileCode"]);
 Write_Log($_POST["FileCode"]);
 Download_File($_POST["FileCode"]);
}

?>


upload.php

<?php

function Display_Upload()
 {

$HTMLDOCS = <<<HTML1

<html>
<body>

<form action= "upload.php" method="post" enctype="multipart/form-data">
<h1><center>IHS Secure File Upload</center></h1>
<table align="center">
<tr><td>Userid: </td>
<td><input type="text" name="userid"> </td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password"></td></tr>

<tr><td>Filename:</td><td>
<input type="file" name="file" id="file" /> </td></tr>

<tr><td colspan="2"><input type="submit" name="submit" value="Upload File"/></td></tr>
</table>
</form>

</body>
</html>
HTML1;

print $HTMLDOCS;
}



// Check to see if the files are ok to be uploaded.
function CheckFile()
 {
 include ("custom.php");
 $ReturnValue = 0;
 if (file_exists("files/" . $_FILES["file"]["name"]))
 {
 $ReturnValue = 1;
 }
 // File Extension Check.
 $pieces = explode (".",$_FILES["file"]["name"]);
 $extension = $pieces[count($pieces)-1];
 // echo "<h1>".$extension."</h1>";
 for ($i=0;$i<count($forbidden_file_extension);$i++)
 {
 if ($extension == $forbidden_file_extension[$i])
 {
 $ReturnValue = 2;
 }
 }
 Return $ReturnValue;
 }

function Upload_File()
 {
 global $success;
 $UploadOK = 0;
 if ($_FILES["file"]["error"] > 0)
 {
 echo "Return Code: " . $_FILES["file"]["error"] . "<br/>";
 }
 else
 {
// echo "Upload: " . $_FILES["file"]["name"] . "<br />";
// echo "Type: " . $_FILES["file"]["type"] . "<br />";
// echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br/>";
// echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br/>";
 $UploadOK = CheckFile();
 if ($UploadOK!= 0)
 {
 if ($UploadOK ==1)
 {
 echo "<h2>". $_FILES["file"]["name"] . " already exists.</h2> ";
 echo "<h2>Go back to <a href=\"index.php\">Main Screen</a>.</h2>";
 exit;
 }
 if ($UploadOK ==2)
 {
 $pieces = explode (".",$_FILES["file"]["name"]);
 $extension = $pieces[count($pieces)-1];
 echo "<h2>File Extension ".$extension." is forbidden.</h2>";
 echo "<h2>Go back to <a href=\"index.php\">Main Screen</a>.</h2>";
 exit;
 }
 }else
 {
 $new_FileName = crypt($_FILES["file"]["name"],'xx');
 $new_FileName = str_replace ("/",".",$new_FileName);
 move_uploaded_file($_FILES["file"]["tmp_name"], "files/" . $new_FileName);
 echo "Stored in: " . "files/" . $new_FileName."</br>";
 $success = 1;
 }
 }
 }

function Write_Description($success)
 {
 include ("custom.php");
 if ($success==1)
 {
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $FileCode = strval(rand (100000000,999999999));
 $FileName = $_FILES["file"]["name"];
 $FileDate = date("Y-m-d");
 $ServerURL = "https:/"."/".$_SERVER['SERVER_NAME'];
 $new_FileName = crypt($_FILES["file"]["name"],'xx');
 $new_FileName = str_replace("/",".",$new_FileName);


 $sql = "INSERT INTO FileLists (FileCode,FileName,Expiration,FileDate,CryptFileName) VALUES('";
 $sql = $sql .$FileCode."','". $FileName."','1 Days','".$FileDate."','".$new_FileName."')";
// echo $sql;
 $result = mysql_query($sql);
 if ($result)
 {
 echo "<h1>File was uploaded successfully</h1>";
 echo "<h3>File Download instruction:</h3>";
 echo "<h4>Point your browser to <a href='".$ServerURL.":4040/download.php'>".$ServerURL.":4040/download.php</a></h4>";
 echo "<h4>Enter ".$FileCode." in the File Code area.</h4>";
 echo "<h4>The file will be available for download until ". date("Y-m-d",strtotime("+7 days")). " and will be deleted from the system.";
 } else
 {
 echo "Fail";
 }
 } else
 {
 echo "File Could not be uploaded... Please try again.";
 }

 }
// Main Program

include ("custom.php");

$success =0;
if (!isset($_POST["userid"]))
 {
 Display_Upload();
 } else
 {
 if ((crypt($_POST["userid"],'xx')==$c_userid) && (crypt($_POST["password"],'xx')==$c_password))
 {
 Upload_File();
 Write_Description ($success);
 } else
 {
 echo "Authentication Failed";
 }
 }

?>