Example #1
0
 public function Start()
 {
     if (jf::CurrentUser() && jf::Check(self::PERMISSION_NAME)) {
         if (isset($_POST['username']) && isset($_POST['password'])) {
             $username = $_POST['username'];
             $password = $_POST['password'];
             if (empty($username) || empty($password)) {
                 echo json_encode(array('status' => false, 'message' => self::PARAMETER_MISSING_MESSAGE));
             } else {
                 if (jf::$User->UserExists($username)) {
                     // If user already exists
                     echo json_encode(array('status' => false, 'message' => self::USER_EXISTS_MESSAGE));
                 } else {
                     // Everything OK. Create a new user and assign the role
                     $userId = jf::$User->CreateUser($username, $password);
                     // Create user
                     $roleId = jf::$RBAC->Roles->TitleId(self::ROLE_NAME);
                     jf::$RBAC->Users->Assign($roleId, $userId);
                     // Assign role to the newly created user
                     echo json_encode(array('status' => true, 'message' => self::SUCCESS_MESSAGE, 'id' => $userId));
                 }
             }
         } else {
             // Required parameters are missing
             echo json_encode(array('status' => false, 'message' => self::PARAMETER_MISSING_MESSAGE));
         }
     } else {
         // User is not authorized
         echo json_encode(array('status' => false, 'message' => self::UNAUTHORIZED_MESSAGE));
     }
     return true;
 }
Example #2
0
 public function Start()
 {
     // If user is already logged in
     if (jf::CurrentUser()) {
         if (isset($_GET["return"])) {
             $return = $_GET["return"];
         } else {
             $return = "";
         }
         $this->Redirect(SiteRoot . $return);
         // Site root does not contain trailing '/'
     }
     // TODO: Implement a secure 'Remember Me'
     if (isset($_POST["Username"]) && isset($_POST['Password'])) {
         $this->Result = jf::Login($_POST['Username'], $_POST['Password']);
     }
     //Login Successful
     if (isset($this->Result) && $this->Result) {
         if (isset($_GET["return"])) {
             $return = $_GET["return"];
         } else {
             $return = "";
         }
         $this->Redirect(SiteRoot . $return);
     }
     return $this->Present();
 }
Example #3
0
 public function Start()
 {
     // Check if the user is logged in and
     // have the required permissions
     if (jf::CurrentUser() && jf::Check(self::PERMISSION_NAME)) {
         // Check if POST parameter present
         if (isset($_POST['username'])) {
             $username = $_POST['username'];
             if (jf::$User->UserExists($username)) {
                 // First remove the user role association
                 $userId = jf::$User->UserID($username);
                 $roleId = jf::$RBAC->Roles->TitleId(self::ROLE_NAME);
                 jf::$RBAC->Users->Unassign($roleId, $userId);
                 // Delete the user
                 jf::$User->DeleteUser($username);
                 echo json_encode(array('status' => true, 'message' => self::SUCCESS_MESSAGE));
             } else {
                 // User does not exists. Error!
                 echo json_encode(array('status' => false, 'message' => self::USER_NOT_EXISTS_MESSAGE));
             }
         } else {
             echo json_encode(array('status' => false, 'message' => self::PARAMETER_MISSING_MESSAGE));
         }
     } else {
         echo json_encode(array('status' => false, 'message' => self::UNAUTHORIZED_MESSAGE));
     }
     return true;
 }
Example #4
0
 public function Start()
 {
     $request = jf::$BaseRequest;
     if (jf::CurrentUser()) {
         // User is logged in, check if the user is authorized
         if (jf::Check("view_contest_chal")) {
             if (($activeContest = \webgoat\ContestDetails::getActive()) !== null) {
                 $this->ContestName = $activeContest[0]['ContestName'];
                 $startTime = $activeContest[0]['StartTimestamp'];
                 $currentTime = time();
                 if ($currentTime < $startTime) {
                     $this->TimeRemaining = $startTime - $currentTime;
                 } else {
                     $challenges = \webgoat\ContestChallenges::getByContestID();
                     if (count($challenges) == 0) {
                         $this->Error = "Currently there are no challenges in this contest";
                     } else {
                         $this->Challenges = $challenges;
                     }
                 }
             } else {
                 $this->Error = "Currently there is no active contest. Check back later!!";
             }
             return $this->Present();
         } else {
             // User is not authorized
             $this->Redirect(SiteRoot);
         }
     } else {
         // User is not logged in
         $this->Redirect(jf::url() . "/user/login?return=/{$request}");
     }
 }
Example #5
0
 function Insert()
 {
     if (jf::$RunMode->IsCLI()) {
         return false;
     }
     $res = jf::SQL("INSERT INTO {$this->TablePrefix()}stats (UserID,SessionID,Timestamp,Page,Query,IP,Host,Protocol,UserAgent) VALUES\n\t\t\t(?,?,?,?,?,?,?,?,?)", jf::CurrentUser() ?: 0, jf::$Session->SessionID(), jf::time(), HttpRequest::URI(), HttpRequest::QueryString(), HttpRequest::IP(), HttpRequest::Host(), HttpRequest::Protocol(), HttpRequest::UserAgent());
     return $res;
 }
Example #6
0
 function Start()
 {
     $this->Username = jf::$XUser->Username();
     jf::$XUser->Logout(jf::CurrentUser());
     setcookie("jframework_rememberme", null, null);
     if (isset($_GET["return"])) {
         $this->Return = $_GET["return"];
     } else {
         $this->Return = "./login";
     }
     return $this->Present();
 }
Example #7
0
 function Start()
 {
     $this->Username = jf::$XUser->Username();
     $Logged = false;
     if (isset($_COOKIE["jframework_rememberme"])) {
         $rememberMeToken = $_COOKIE["jframework_rememberme"];
         $userID = jf::LoadGeneralSetting("rememberme_" . $rememberMeToken);
         if ($userID > 0) {
             $Result = jf::$XUser->ForceLogin($userID);
             $Logged = true;
         }
     }
     if (isset($_POST["Username"])) {
         $Username = $_POST['Username'];
         $Password = $_POST['Password'];
         $loginResult = jf::$XUser->Login($Username, $Password);
         if ($loginResult == false) {
             $UserID = jf::$XUser->UserID($Username);
             $res = jf::$XUser->LastError;
             if ($res == \jf\ExtendedUserErrors::Inactive) {
                 $ErrorString = "Your account is not activated.";
             } elseif ($res == \jf\ExtendedUserErrors::InvalidCredentials or $res == \jf\ExtendedUserErrors::NotFound) {
                 $ErrorString = "Invalid Credentials.";
             } elseif ($res == \jf\ExtendedUserErrors::Locked) {
                 $ErrorString = "Your account is locked. Try again in " . floor(jf::$XUser->LockTime($Username) / 60) . " minute(s).";
             } elseif ($res == \jf\ExtendedUserErrors::PasswordExpired) {
                 $Link = "./reset?user={$UserID}";
                 $ErrorString = "Your password is expired. You should <a href='{$Link}'>change your password</a>.";
             } elseif ($res == \jf\ExtendedUserErrors::TemporaryValidPassword) {
                 $Link = "./reset?user={$UserID}&temp={$Password}";
                 $ErrorString = "This is a temporary password. You should <a href='{$Link}'>reset your password</a> now.";
             }
             $Logged = false;
             $this->Error = $ErrorString;
         } else {
             $Logged = true;
             if (isset($_POST['Remember'])) {
                 $timeout = 60 * 60 * 24 * 30;
                 $rememberMeToken = jf::$Security->RandomToken();
                 jf::SaveGeneralSetting("rememberme_" . $rememberMeToken, jf::CurrentUser(), $timeout);
                 setcookie('jframework_rememberme', $rememberMeToken, jf::time() + $timeout);
             }
         }
     }
     if ($Logged == true) {
         if (isset($_GET['return'])) {
             $this->Redirect($_GET['return']);
         }
         $this->Success = true;
     }
     return $this->Present();
 }
Example #8
0
 public function Start()
 {
     // If user is logged in
     if (jf::CurrentUser()) {
         jf::Logout();
     }
     if (isset($_GET["return"])) {
         $Return = $_GET["return"];
     } else {
         $Return = "";
     }
     $this->Redirect(SiteRoot . $Return);
 }
Example #9
0
 public function Start()
 {
     if (jf::CurrentUser()) {
         if (jf::Check("contest")) {
             if (isset($_POST['challenge']) && isset($_POST['name']) && isset($_POST['points']) && isset($_POST['flag'])) {
                 $hashedFlag = md5($_POST['flag']);
                 $activeContest = \webgoat\ContestDetails::getActive();
                 $activeContestID = $activeContest[0]['ID'];
                 $data = array('ContestID' => $activeContestID, 'ChallengeName' => $_POST['challenge'], 'NameToDisplay' => $_POST['name'], 'Points' => $_POST['points'], 'CorrectFlag' => $hashedFlag);
                 \webgoat\ContestChallenges::add($data);
                 echo json_encode(array('status' => true, 'message' => 'Challenge successfully added'));
                 return true;
             }
         }
     }
 }
Example #10
0
 private function addSubmission($challenge)
 {
     $challengeDetails = \webgoat\ContestChallenges::getByName($challenge);
     $flag = $_POST['flag'];
     $ip = \jf\HttpRequest::IP();
     $challengeID = $challengeDetails[0]['ID'];
     $userID = jf::CurrentUser();
     $data = array('UserID' => $userID, 'ChallengeID' => $challengeID, 'Flag' => $flag, 'IP' => $ip, 'timestamp' => time());
     \webgoat\ContestSubmissions::add($data);
     \webgoat\ContestChallenges::incrementTotalAttempts($challenge);
     if (\webgoat\ContestSubmissions::evaluate($challengeID, $flag)) {
         $this->Submission = 1;
         // Increment complete count
         \webgoat\ContestChallenges::incrementCompletedCount($challenge);
     } else {
         $this->Submission = 0;
     }
 }
Example #11
0
 public function Start()
 {
     if (jf::CurrentUser()) {
         $userName = jf::$XUser->Username();
         $oldPass = $_POST['old_password'];
         $newPass = $_POST['new_password'];
         $cnfNewPass = $_POST['cnew_password'];
         if ($newPass != $cnfNewPass) {
             echo json_encode(array('status' => false, 'error' => 'Password and Confirm Password do not match'));
         } elseif (!jf::Login($userName, $oldPass)) {
             echo json_encode(array('status' => false, 'error' => 'Old Password is incorrect'));
         } else {
             jf::$User->EditUser($userName, $userName, $newPass);
             echo json_encode(array('status' => true, 'message' => 'Password successfully updated'));
         }
     } else {
         echo json_encode(array('status' => false, 'error' => 'You are not authorized for this action'));
     }
     return true;
 }
Example #12
0
 public function Start()
 {
     if (jf::CurrentUser()) {
         if (jf::Check("contest")) {
             // User is authorized
             if (isset($_POST['contest_submit'])) {
                 // Request to store the contest in the database
                 $this->addContest();
             }
             if (\webgoat\ContestDetails::isActivePresent()) {
                 // If an active contest is present
                 $contestDetails = \webgoat\ContestDetails::getActive();
                 $contestChallenges = \webgoat\ContestChallenges::getByContestID($contestDetails[0]['ID']);
                 $contestUsers = \webgoat\ContestUsers::getAll();
                 $this->ContestName = $contestDetails[0]['ContestName'];
                 $this->ContestStart = date("d/m/Y h:i:s A", $contestDetails[0]['StartTimestamp']);
                 $this->ContestEnd = date("d/m/Y h:i:s A", $contestDetails[0]['EndTimestamp']);
                 $this->UserCount = count($contestUsers);
                 $this->ChallengeCount = count($contestChallenges);
                 $this->Challenges = $contestChallenges;
                 $this->insertNewChallenges();
             } else {
                 // Show the option to start a contest
                 $this->noActiveContest = true;
             }
             return $this->Present();
         } else {
             // User is not authorized
             $this->Redirect(SiteRoot);
             // Redirect to home page
         }
     } else {
         // User is not authenticated
         $this->Redirect(jf::url() . "/user/login?return=/" . jf::$BaseRequest);
     }
 }
Example #13
0
 static function Log($Subject, $Content, $Severity = 0)
 {
     if (jf::$App) {
         return jf::SQL("INSERT INTO " . jf::TablePrefix() . "logs (Subject,Data,Severity,UserID,SessionID,Timestamp) \n\t\t" . "VALUES (?,?,?,?,?,?)", $Subject, $Content, $Severity, jf::CurrentUser(), jf::$Session->SessionID(), jf::time());
     }
 }
Example #14
0
 /**
  * Enforce a permission on current user
  * @param string|integer $Permission path or title or ID of permission
  */
 function Enforce($Permission)
 {
     if (jf::CurrentUser() === null) {
         jf::run("view/_internal/error/401", array("Permission" => $Permission));
         exit;
     }
     if (!$this->Check($Permission)) {
         jf::run("view/_internal/error/403", array("Permission" => $Permission));
         exit;
     }
 }
Example #15
0
 /**
  * Return count of roles for a user
  * 
  * @param integer $UserID
  *        	optional
  * @return integer
  */
 function RoleCount($UserID = null)
 {
     if ($UserID === null) {
         $UserID = jf::CurrentUser();
     }
     $Res = jf::SQL("SELECT COUNT(*) AS Result FROM {$this->TablePrefix()}rbac_userroles WHERE UserID=?", $UserID);
     return $Res[0]['Result'];
 }
Example #16
0
 /**
  * returns Username of a user
  *
  * @param Integer $UserID
  * @return String
  */
 function Username($UserID = null)
 {
     if ($UserID === null) {
         $UserID = jf::CurrentUser();
     }
     $Result = jf::SQL("SELECT Username FROM {$this->TablePrefix()}users WHERE ID=?", $UserID);
     if ($Result) {
         return $Result[0]['Username'];
     } else {
         return null;
     }
 }
Example #17
0
 /**
  * delete all user settings
  * @throws \Exception
  * @return int, number of rows
  */
 function DeleteAllUser($UserID = null)
 {
     if ($UserID === null) {
         if (jf::CurrentUser() == null) {
             throw new \Exception("Can not load user options without a logged in user.");
         } else {
             $UserID = jf::CurrentUser();
         }
     }
     $r = jf::SQL("DELETE FROM {$this->TablePrefix()}options WHERE UserID=?", $UserID);
     return $r;
 }
Example #18
0
 public function Start()
 {
     if (jf::CurrentUser()) {
         // Authorize the user
         if (jf::Check('workshop')) {
             $hiddenLessons = jf::LoadGeneralSetting("hiddenWorkshopLessons");
             // If request to hide the lesson
             if (isset($_POST['hide'])) {
                 if ($hiddenLessons === null) {
                     // If first request i.e settings not present
                     $hiddenLessons = array($_POST['hide']);
                 } else {
                     array_push($hiddenLessons, $_POST['hide']);
                 }
                 jf::SaveGeneralSetting("hiddenWorkshopLessons", $hiddenLessons);
                 echo json_encode(array('status' => true));
                 return true;
             }
             // If request to show the lesson
             if (isset($_POST['show'])) {
                 if ($hiddenLessons !== null) {
                     $position = array_search($_POST['show'], $hiddenLessons);
                     if ($position !== false) {
                         unset($hiddenLessons[$position]);
                     }
                 }
                 jf::SaveGeneralSetting("hiddenWorkshopLessons", $hiddenLessons);
                 echo json_encode(array('status' => true));
                 return true;
             }
             // Get the list of all the lessons/categories
             $this->allCategoryLesson = jf::LoadGeneralSetting("categoryLessons");
             $this->hiddenLessons = $hiddenLessons;
             // To generate 'overview' section of the dashboard
             // Store all the stats
             $obj = new \webgoat\WorkshopUsers();
             if (($workshopUsers = $obj->getAll()) === null) {
                 // Will return 'null' if no users are present
                 $workshopUsers = array();
                 // Initialize it to empty array
             }
             $this->totalUsers = count($workshopUsers);
             $this->totalCategories = count($this->allCategoryLesson);
             $lessonCount = 0;
             foreach ($this->allCategoryLesson as $category => $lessons) {
                 $lessonCount += count($lessons);
             }
             $this->totalLessons = $lessonCount;
             $this->totalVisibleLessons = $lessonCount - count($this->hiddenLessons);
             // For each lesson store a list of users
             // who have completed it
             $lessonsCompletedBy = array();
             $lessonPrefix = "completed_webgoat\\";
             foreach ($this->allCategoryLesson as $category => $lessons) {
                 foreach ($lessons as $lesson) {
                     $lessonsCompletedBy[$lesson[0]] = array();
                     // Index 0 is for name
                     foreach ($workshopUsers as $user) {
                         if (jf::LoadUserSetting($lessonPrefix . $lesson[0], $user['ID'])) {
                             array_push($lessonsCompletedBy[$lesson[0]], $user['Username']);
                         }
                     }
                 }
             }
             // To generate the reports page
             $this->reports = $lessonsCompletedBy;
             // To generate analytics
             $noOfLessonsInCategories = array(array('Category', 'No of Lessons'));
             // Initialize with heading
             foreach ($this->allCategoryLesson as $category => $lessons) {
                 array_push($noOfLessonsInCategories, array($category, count($lessons)));
             }
             $this->analytics = $noOfLessonsInCategories;
             return $this->Present();
         } else {
             // User not authorized
             $this->Redirect(SiteRoot);
             // Redirect to home page instead of Login Page
         }
     } else {
         // User not authenticated
         $this->Redirect(jf::url() . "/user/login?return=/" . jf::$BaseRequest);
     }
 }
Example #19
0
 /**
  * @depends testCreate
  */
 function testLogin()
 {
     $userid = jf::$User->CreateUser("myUsername", "myPassword");
     $this->assertFalse(jf::$User->IsLoggedIn($userid));
     $this->assertFalse(jf::$User->Login("myUsernamE", "wrong_password"));
     $this->assertFalse(jf::$User->IsLoggedIn($userid));
     $this->assertFalse(jf::$User->Login("wrong_username", "myPassword"));
     $this->assertFalse(jf::$User->IsLoggedIn($userid));
     $this->assertTrue(jf::$User->Login("myUsernamE", "myPassword"));
     $this->assertTrue(jf::$User->IsLoggedIn($userid));
     jf::$User->Logout($userid);
     $this->assertFalse(jf::$User->IsLoggedIn($userid));
     $this->assertTrue(jf::$User->Login("myUsername", "myPassword"));
     //already logged in, default mode is overwrite
     $this->assertTrue($r = jf::$User->Login("myUsername", "myPassword"));
     jf::$User->Login("wrong_username", "myPassword");
     $this->assertTrue(jf::$User->IsLoggedIn($userid));
     $this->assertEquals($userid, jf::CurrentUser());
     jf::$User->Logout();
     $this->assertFalse(jf::$User->IsLoggedIn($userid));
 }
Example #20
0
        </button>
        <div class="collapse navbar-collapse navHeaderCollapse">
            <ul class="nav navbar-nav navbar-right">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="<?php 
echo jf::url() . '/about';
?>
">About</a></li>
                <li><a href="#">Documentation</a></li>
                <li><a href="<?php 
echo GITHUB_URL;
?>
" target="_blank">Github</a></li>
                <li><a href="#contact" data-toggle="modal">Contact</a></li>
                <?php 
if (jf::CurrentUser()) {
    ?>
                    <li><a href="<?php 
    echo jf::url() . '/user/logout';
    ?>
">Logout</a></li>
                <?php 
}
?>
            </ul>
        </div>
    </div>
</div>

<div class="container">
    <div class="jumbotron">
Example #21
0
 public function Handle($request)
 {
     // This gives complete request path
     $request = jf::$BaseRequest;
     //FIXME: Fix JCatchControl so that this is not required
     if (jf::CurrentUser()) {
         // If user is logged in
         // Check if the user has permissions
         // to view the challenges
         if (jf::Check('view_single_chal')) {
             // Extract the relative request path
             // i.e the path after the controller URL
             // Ex: If request is http://localhost/webgoatphp/mode/single/challenges/HTTPBasics/static/test
             // $request will be mode/single/challenges/HTTPBasics/static/test
             // $relativePath will be HTTPBasics/static/test
             $relativePath = $this->getRelativePath($request);
             $absolutePath = LESSON_PATH . $relativePath;
             if (strpos($relativePath, "/static/") !== false) {
                 if (file_exists($absolutePath)) {
                     $FileMan = new \jf\DownloadManager();
                     return $FileMan->Feed($absolutePath);
                 }
             } else {
                 $nameOfLesson = stristr($relativePath, "/", true);
                 \webgoat\LessonScanner::loadClasses();
                 if (strpos($relativePath, "reset/") !== false) {
                     $lessonNameWithNS = "\\webgoat\\" . $nameOfLesson;
                     $obj = new $lessonNameWithNS();
                     $obj->reset();
                     echo json_encode(array("status" => true));
                     return true;
                 } else {
                     if (isset($_GET['refresh']) || !jf::LoadGeneralSetting("categoryLessons")) {
                         \webgoat\LessonScanner::run();
                     }
                     $this->allCategoryLesson = jf::LoadGeneralSetting("categoryLessons");
                     try {
                         $lessonObj = \webgoat\LessonScanner::getLessonObject($nameOfLesson);
                         $lessonObj->start();
                         $this->lessonTitle = $lessonObj->getTitle();
                         $this->hints = $lessonObj->getHints();
                         $this->htmlContent = $lessonObj->getContent();
                         $this->nameOfLesson = $nameOfLesson;
                         $secureCoding = $lessonObj->isSecureCodingAllowed();
                         $sourceCodeToDisplay = "";
                         if ($secureCoding['status'] === true) {
                             $sourceCode = file($absolutePath . "index.php");
                             $firstLine = $sourceCode[$secureCoding['start']];
                             $this->indentSize = strlen($firstLine) - strlen(ltrim($firstLine));
                             for ($i = $secureCoding['start']; $i < $secureCoding['end']; $i++) {
                                 $sourceCodeToDisplay .= $this->removeWhitespaces($sourceCode[$i]) . "\n";
                             }
                             $this->sourceCode = $sourceCodeToDisplay;
                         }
                         // To show complete PHP Code
                         $sourceCode = file_get_contents($absolutePath . "index.php");
                         $this->completeSourceCode = htmlentities($sourceCode);
                         if (isset($_POST['sourceCode'])) {
                             // Code to handle source code evaluation
                         }
                     } catch (Exception $e) {
                         //$this->error = "Lesson Not found. Please select a lesson.";
                         $this->error = $e->getMessage();
                     }
                     header("X-XSS-Protection: 0");
                     // Disable XSS protection
                     return $this->Present();
                 }
             }
         } else {
             // Not sufficient permissions, redirect
             // to home page of the application
             $this->Redirect(SiteRoot);
         }
     } else {
         // User not logged in
         $this->Redirect(jf::url() . "/user/login?return=/{$request}");
     }
 }