• Activity
  • Votes
  • Comments
  • New
  • All activity
    1. Programming Challenge - Find path from city A to city B with least traffic controls inbetween.

      Previous challenges Hi, it's been very long time from last Programming Challenge, and I'd like to revive the tradition. The point of programming challenge is to create your own solution, and if...

      Previous challenges

      Hi, it's been very long time from last Programming Challenge, and I'd like to revive the tradition.

      The point of programming challenge is to create your own solution, and if you're bored, even program it in your favourite programming language. Today's challenge isn't mine. It was created by ČVUT FIKS (year 5, season 2, challenge #4).

      You need to transport plans for your quantum computer through Totalitatia. The problem is, that Totalitatia's government would love to have the plans. And they know you're going to transport the computer through the country. You'll receive number N, which denotes number of cities on the map. Then, you'll get M paths, each going from one city to another. Each path has k traffic controls. They're not that much effective, but the less of them you have to pass, the better. Find path from city A to city B, so the maximum number of traffic controls between any two cities is minimal. City A is always the first one (0) and city B is always the last one (N-1).

      Input format:

      N
      M
      A1 B1 K1
      A2 B2 K2
      ...
      

      On the first two lines, you'll get numbers N (number of cities) and M (number of paths). Than, on next M lines, you'll get definition of a path. The definition looks like 1 2 6, where 1 is id of first city and 2 is id of second city (delimited by a space). You can go from city 1 to city 2, or from city 2 to city 1. The third number (6) is number of traffic controls.

      Output format:

      Single number, which denotes maximum number of traffic controls encountered on one path.

      Hint: This means, that path that goes via roads with numbers of traffic controls 4 4 4 is better than path via roads with numbers of traffic controls 1 5 1. First example would have output 4, the second one would have output 5.

      Example:

      IN:

      4
      5
      0 1 3
      0 2 2
      1 2 1
      1 3 4
      2 3 5
      

      OUT:

      4
      

      Solution: The optimal path is either 0 2 1 3 or 0 1 3.

      Bonus

      • Describe time complexity of your algorithm.
      • If multiple optimal paths exist, find the shortest one.
      • Does your algorithm work without changing the core logic, if the source city and the target city is not known beforehand (it changes on each input)?
      • Do you use special collection to speed up minimum value search?

      Hints

      Special collection to speed up algorithm

      13 votes
    2. Programming Challenge: Anagram checking.

      It's been over a week since the last programming challenge and the previous one was a bit more difficult, so let's do something easier and more accessible to newer programmers in particular. Write...

      It's been over a week since the last programming challenge and the previous one was a bit more difficult, so let's do something easier and more accessible to newer programmers in particular. Write a function that takes two strings as input and returns true if they're anagrams of each other, or false if they're not.

      Extra credit tasks:

      • Don't consider the strings anagrams if they're the same barring punctuation.
      • Write an efficient implementation (in terms of time and/or space complexity).
      • Minimize your use of built-in functions and methods to bare essentials.
      • Write the worst--but still working--implementation that you can conceive of.
      24 votes
    3. Why open source projects don't charge (while keeping the code open)?

      I'd gladly pay a reasonable price for professional packages/support for programs like Emacs/Melpa, Debian, and Xfce. As a user, I empathize with the complaints by developers that are constantly...

      I'd gladly pay a reasonable price for professional packages/support for programs like Emacs/Melpa, Debian, and Xfce. As a user, I empathize with the complaints by developers that are constantly overworked. Even if this doesn't generate enough money to pay for everything, it might be enough to hire someone to handle the issues and communities, something that clearly drains their efforts, especially because programmers tend to prefer technical challenges rather than dealing with people.

      I understand that many projects accept donations, but I think providing an actual reward (even if its something minimal, like an updated package instead of having to build it from source) might be a good way to get resources and avoid developer burndown.

      11 votes
    4. Code Quality Tip: Cyclomatic complexity in depth.

      Preface Recently I briefly touched on the subject of cyclomatic complexity. This is an important concept for any programmer to understand and think about as they write their code. In order to...

      Preface

      Recently I briefly touched on the subject of cyclomatic complexity. This is an important concept for any programmer to understand and think about as they write their code. In order to provide a more solid understanding of the subject, however, I feel that I need to address the topic more thoroughly with a more practical example.


      What is cyclomatic complexity?

      The concept of "cyclomatic complexity" is simple: the more conditional branching and looping in your code, the more complex--and therefore the more difficult to maintain--that code is. We can visualize this complexity by drawing a diagram that illustrates the flow of logic in our program. For example, let's take the following toy example of a user login attempt:

      <?php
      
      $login_data = getLoginCredentialsFromInput();
      
      $login_succeeded = false;
      $error = '';
      if(usernameExists($login_data['username'])) {
          $user = getUser($login_data['username']);
          
          if(!isDeleted($user)) {
              if(!isBanned($user)) {
                  if(!loginRateLimitReached($user)) {
                      if(passwordMatches($user, $login_data['password'])) {
                          loginUser($user);
                          $login_succeeded = true;
                      } else {
                          $error = getBadPasswordError();
                          logBadLoginAttempt();
                      }
                  } else {
                      $error = getLoginRateLimitError($user);
                  }
              } else {
                  $error = getUserBannedError($user);
              }
          } else {
              $error = getUserDeletedError($user);
          }
      } else {
          $error = getBadUsernameError($login_data['username']);
      }
      
      if($login_succeeded) {
          sendSuccessResponse();
      } else {
          sendErrorResponse($error);
      }
      
      ?>
      

      A diagram for this logic might look something like this:

      +-----------------+
      |                 |
      |  Program Start  |
      |                 |
      +--------+--------+
               |
               |
               v
      +--------+--------+    +-----------------+
      |                 |    |                 |
      |    Username     +--->+    Set Error    +--+
      |    Exists?      | No |                 |  |
      |                 |    +-----------------+  |
      +--------+--------+                         |
               |                                  |
           Yes |                                  |
               v                                  |
      +--------+--------+    +-----------------+  |
      |                 |    |                 |  |
      |  User Deleted?  +--->+    Set Error    +->+
      |                 | Yes|                 |  |
      +--------+--------+    +-----------------+  |
               |                                  |
            No |                                  |
               v                                  |
      +--------+--------+    +-----------------+  |
      |                 |    |                 |  |
      |  User Banned?   +--->+    Set Error    +->+
      |                 | Yes|                 |  |
      +--------+--------+    +-----------------+  |
               |                                  |
            No |                                  |
               v                                  |
      +--------+--------+    +-----------------+  |
      |                 |    |                 |  |
      |   Login Rate    +--->+    Set Error    +->+
      | Limit Reached?  | Yes|                 |  |
      |                 |    +-----------------+  |
      +--------+--------+                         |
               |                                  |
            No |                                  |
               v                                  |
      +--------+--------+    +-----------------+  |
      |                 |    |                 |  |
      |Password Matches?+--->+    Set Error    +->+
      |                 | No |                 |  |
      +--------+--------+    +-----------------+  |
               |                                  |
           Yes |                                  |
               v                                  |
      +--------+--------+    +----------+         |
      |                 |    |          |         |
      |   Login User    +--->+ Converge +<--------+
      |                 |    |          |
      +-----------------+    +---+------+
                                 |
                                 |
               +-----------------+
               |
               v
      +--------+--------+
      |                 |
      |   Succeeded?    +-------------+
      |                 | No          |
      +--------+--------+             |
               |                      |
           Yes |                      |
               v                      v
      +--------+--------+    +--------+--------+
      |                 |    |                 |
      |  Send Success   |    |   Send Error    |
      |    Message      |    |    Message      |
      |                 |    |                 |
      +-----------------+    +-----------------+
      

      It's important to note that between nodes in this directed graph, you can find certain enclosed regions being formed. Specifically, each conditional branch that converges back into the main line of execution generates an additional region. The number of these distinct enclosed regions is directly proportional to the level of cyclomatic complexity of the system--that is, more regions means more complicated code.


      Clocking out early.

      There's an important piece of information I noted when describing the above example:

      . . . each conditional branch that converges back into the main line of execution generates an additional region.

      The above example is made complex largely due to an attempt to create a single exit point at the end of the program logic, causing these conditional branches to converge and thus generate the additional enclosed regions within our diagram.

      But what if we stopped trying to converge back into the main line of execution? What if, instead, we decided to interrupt the program execution as soon as we encountered an error? Our code might look something like this:

      <?php
      
      $login_data = getLoginCredentialsFromInput();
      
      if(!usernameExists($login_data['username'])) {
          sendErrorResponse(getBadUsernameError($login_data['username']));
          return;
      }
      
      $user = getUser($login_data['username']);
      if(isDeleted($user)) {
          sendErrorResponse(getUserDeletedError($user));
          return;
      }
      
      if(isBanned($user)) {
          sendErrorResponse(getUserBannedError($user));
          return;
      }
      
      if(loginRateLimitReached($user)) {
          logBadLoginAttempt($user);
          sendErrorResponse(getLoginRateLimitError($user));
          return;
      }
      
      if(!passwordMatches($user, $login_data['password'])) {
          logBadLoginAttempt($user);
          sendErrorResponse(getBadPasswordError());
          return;
      }
      
      loginUser($user);
      sendSuccessResponse();
      
      ?>
      

      Before we've even constructed a diagram for this logic, we can already see just how much simpler this logic is. We don't need to traverse a tree of if statements to determine which error message has priority to be sent out, we don't need to attempt to follow indentation levels, and our behavior on success is right at the very end and at the lowest level of indentation, where it's easily and obviously located at a glance.

      Now, however, let's verify this reduction in complexity by examining the associated diagram:

      +-----------------+
      |                 |
      |  Program Start  |
      |                 |
      +--------+--------+
               |
               |
               v
      +--------+--------+    +-----------------+
      |                 |    |                 |
      |    Username     +--->+   Send Error    |
      |    Exists?      | No |    Message      |
      |                 |    |                 |
      +--------+--------+    +-----------------+
               |
           Yes |
               v
      +--------+--------+    +-----------------+
      |                 |    |                 |
      |  User Deleted?  +--->+   Send Error    |
      |                 | Yes|    Message      |
      +--------+--------+    |                 |
               |             +-----------------+
            No |
               v
      +--------+--------+    +-----------------+
      |                 |    |                 |
      |  User Banned?   +--->+   Send Error    |
      |                 | Yes|    Message      |
      +--------+--------+    |                 |
               |             +-----------------+
            No |
               v
      +--------+--------+    +-----------------+
      |                 |    |                 |
      |   Login Rate    +--->+   Send Error    |
      | Limit Reached?  | Yes|    Message      |
      |                 |    |                 |
      +--------+--------+    +-----------------+
               |
            No |
               v
      +--------+--------+    +-----------------+
      |                 |    |                 |
      |Password Matches?+--->+   Send Error    |
      |                 | No |    Message      |
      +--------+--------+    |                 |
               |             +-----------------+
           Yes |
               v
      +--------+--------+
      |                 |
      |   Login User    |
      |                 |
      +--------+--------+
               |
               |
               v
      +--------+--------+
      |                 |
      |  Send Success   |
      |    Message      |
      |                 |
      +-----------------+
      

      Something should immediately stand out here: there are no enclosed regions in this diagram! Furthermore, even our new diagram is much simpler to follow than the old one was.


      Reality is rarely simple.

      The above is a really forgiving example. It has no loops, and loops are going to create enclosed regions that can't be broken apart so easily; it has no conditional branches that are so tightly coupled with the main path of execution that they can't be broken up; and the scope of functionality and side effects are minimal. Sometimes you can't break those regions up. So what do we do when we inevitably encounter these cases?

      High cyclomatic complexity in your program as a whole is inevitable for sufficiently large projects, especially in a production environment, and your efforts to reduce it can only go so far. In fact, I don't recommend trying to remove all or even most instances of cyclomatic complexity at all--instead, you should just be keeping the concept in mind to determine whether or not a function, method, class, module, or other component of your system is accumulating technical debt and therefore in need of refactoring.

      At this point, astute readers might ask, "How does refactoring help if the cyclomatic complexity doesn't actually go away?", and this is a valid concern. The answer to that is simple, however: we're hiding complexity behind abstractions.

      To test this, let's forget about cyclomatic complexity for a moment and instead focus on simplifying the refactored version of our toy example using abstraction:

      <?php
      
      function handleLoginAttempt($login_data) {
          if(!usernameExists($login_data['username'])) {
              sendErrorResponse(getBadUsernameError($login_data['username']));
              return;
          }
      
          $user = getUser($login_data['username']);
          if(isDeleted($user)) {
              sendErrorResponse(getUserDeletedError($user));
              return;
          }
      
          if(isBanned($user)) {
              sendErrorResponse(getUserBannedError($user));
              return;
          }
      
          if(loginRateLimitReached($user)) {
              logBadLoginAttempt($user);
              sendErrorResponse(getLoginRateLimitError($user));
              return;
          }
      
          if(!passwordMatches($user, $login_data['password'])) {
              logBadLoginAttempt($user);
              sendErrorResponse(getBadPasswordError());
              return;
          }
      
          loginUser($user);
          sendSuccessResponse();
      }
      
      $login_data = getLoginCredentialsFromInput();
      
      handleLoginAttempt($login_data);
      
      ?>
      

      The code above is functionally identical to our refactored example from earlier, but has an additional abstraction via a function. Now we can diagram this higher-level abstraction as follows:

      +-----------------+
      |                 |
      |  Program Start  |
      |                 |
      +--------+--------+
               |
               |
               v
      +--------+--------+
      |                 |
      |  Attempt Login  |
      |                 |
      +-----------------+
      

      This is, of course, a pretty extreme example, but this is how we handle thinking about complex program logic. We abstract it down to the barest basics so that we can visualize, in its simplest form, what the program is supposed to do. We don't actually care about the implementation unless we're digging into that specific part of the system, because otherwise we would be so bogged down by the details that we wouldn't be able to reason about what our program is supposed to do.

      Likewise, we can use these abstractions to hide away the cyclomatic complexity underlying different components of our software. This keeps everything clean and clutter-free in our head. And the more we do to keep our smaller components simple and easy to think about, the easier the larger components are to deal with, no matter how much cyclomatic complexity all of those components share as a collective.


      Final Thoughts

      Cyclomatic complexity isn't a bad thing to have in your code. The concept itself is only intended to be used as one of many tools to assess when your code is accumulating too much technical debt. It's a warning sign that you may need to change something, nothing more. But it's an incredibly useful tool to have available to you and you should get comfortable using it.

      As a general rule of thumb, you can usually just take a glance at your code and assess whether or not there's too much cyclomatic complexity in a component by looking for either of the following:

      • Too many loops and/or conditional statements nested within each other, i.e. you have a lot of indentation.
      • Many loops in the same function/method.

      It's not a perfect rule of thumb, but it's useful for at least 90% of your development needs, and there will inevitably be cases where you will prefer to accept some greater cyclomatic complexity because there is some benefit that makes it a better trade-off. Making that judgment is up to you as a developer.

      As always, I'm more than willing to listen to feedback and answer any questions!

      25 votes
    5. What programming language do you think deserves more credit?

      My pick is Perl5. Even though a lot people (mostly those who’ve never touched Perl) say it’s a “write only” language, I think it does a lot right. It’s easy to prototype with, and it gives you a...

      My pick is Perl5. Even though a lot people (mostly those who’ve never touched Perl) say it’s a “write only” language, I think it does a lot right. It’s easy to prototype with, and it gives you a lot of freedom in how you want to solve a problem; which I think is one of the most important features of a programming language.

      I’d like to know what your picks are!

      33 votes
    6. I want to get into IT as a career, but I have no previous experience. What essential skills should I know?

      I've recently started taking some IT and programming classes at a local college because I've always been interested in IT as a career but I've never had any sort of professional experience in the...

      I've recently started taking some IT and programming classes at a local college because I've always been interested in IT as a career but I've never had any sort of professional experience in the field. Are there any skills that I need to definitely know, or any sort of certifications that I can get in order to get my foot in the door and start applying for IT focused jobs?

      24 votes
    7. Web developers - What is your stack?

      As someone who is not mainly a web developer, I can barely grasp the immensity of options when it comes to writing a web application. So far everything I've written has been using PHP and the Slim...

      As someone who is not mainly a web developer, I can barely grasp the immensity of options when it comes to writing a web application.

      So far everything I've written has been using PHP and the Slim microframework. PHP because I don't use languages like Python/Ruby/JS that much so I didn't have any prior knowledge of those, and I've found myself to be fairly productive with it. Slim because I didn't want a full-blown framework with 200 files to configure.

      I've tried Go because I've used it in the past but I don't see it to be very fit when it comes to websites, I think it's fine for small microservices but doing MVC was a chore, maybe there's a framework out there that solves this.

      As for the frontend I've been trying to use as little JavaScript as possible, always vanilla. As of HTML and CSS I'm no designer so I kind of get by copying code and tweaking things here and there.

      However I've started a slightly bigger project and I don't fancy myself writing everything from scratch (specially security) besides, ORMs can be useful. Symfony4 is what I've been using for a couple of days, but I've had trouble setting up debugging, and the community/docs don't seem that great since this version is fairly new; so I'm considering trying out something more popular like Django.

      So this is why I created the post, I know this will differ greatly depending on the use-case. But I would like to do a quick survey and hear some of your recommendations, both on the backend and frontend. Besides I think it's a good topic for discussion.

      Cheers!

      20 votes
    8. Does anyone here work in infosec? If so, which laptops are you allowed to use?

      I’ve recently gotten to speak with a few folks who work at an enterprise security company. I asked what their security researchers set as company rules for allowed laptops. My one datapoint so far...

      I’ve recently gotten to speak with a few folks who work at an enterprise security company. I asked what their security researchers set as company rules for allowed laptops. My one datapoint so far is “Dell or Apple.” So for example, no Thinkpad X1 Carbon, which is arguably the best work laptop.

      I am curious what other large security companies (or any of you security minded folks) set as rules for trusted laptops. Can anyone share their lists and theories as to why I heard Dell and Apple? BIOS is more trustworthy?

      10 votes
    9. What do you think is one thing every sysadmin should know how to do?

      Blatantly stealing from the excellent post by /u/judah, I figured I'd make a sysadmin version because sysadmins tend to be underrepresented in tech discussions. Please keep your answers as...

      Blatantly stealing from the excellent post by /u/judah, I figured I'd make a sysadmin version because sysadmins tend to be underrepresented in tech discussions. Please keep your answers as cross-platform as possible without being uselessly generic.

      I'll start. Realize that the system is going to go down, and accept that reality. Accept failure. How you respond to failure is how people who aren't sysadmins will see and value you.

      8 votes
    10. What's your OS and how does it look?

      Just a bit curious. Currently, mine looks like this. It runs Elementary OS, however considering hijacking it to Bedrock Linux, mainly to get cutting edge software from the AUR (for stuff like...

      Just a bit curious. Currently, mine looks like this. It runs Elementary OS, however considering hijacking it to Bedrock Linux, mainly to get cutting edge software from the AUR (for stuff like Firefox and GIMP) without losing all my data. I think I'll wait for Bedrock to go stable first, though.

      It uses the ePapirus icon theme, which is just Papirus with better support for Elementary's UI. GTK theme is (if I remember correctly) Qogir and the Plank theme is the GTK one. What do yours look like?

      23 votes
    11. 8th Layer to the OSI Model, Meta-application Layer

      The Meta-application layer works by using a number of pre-configured free-to-use web applications such as FB messenger, gmail, skype, gchat, yahoo email, etc to establish a connection and transmit...

      The Meta-application layer works by using a number of pre-configured free-to-use web applications such as FB messenger, gmail, skype, gchat, yahoo email, etc to establish a connection and transmit data over top the application layer.

      It's purpose is to establish a meta-layer for new applications to make use of, to decrease centralization, and to increase privacy. Take the power back from big corporations, and put it back in with the People! (or some such thing, maybe...).

      So each end of the communication would check some pre-configured number of free-online web apps for a code/key from the other side. Once found that key would determine the ordering, frequency, and mediums to use for communication. Such as: gmail - first message, skype - second message, yahoo email - third and forth message, repeat 10x, then reverse order, repeat 10x, and then start over again or better yet some hard-to-discern pattern.

      Privacy would be increased through both obscurity (typically not a good way to do security) and through the use of a multitude of different web applications, each with their own varying degrees of security.

      The actual messages would be the binary code...or for a more directed-application - text messages... Communication would be slow....but possible?

      Anyways, that thought popped into my head so I thought I'd share it in case it took your own brain to any interesting places :)

      4 votes
    12. Working as a contractor in IT

      Does anyone have any experience working as a contractor in the IT field? I have 4 years of experience in the IT industry, all of it as a full time direct hire. I may have an opportunity to work...

      Does anyone have any experience working as a contractor in the IT field? I have 4 years of experience in the IT industry, all of it as a full time direct hire. I may have an opportunity to work for a very large company on a 2 year contract at fairly reasonable salary increase. The most important part to me is that I will be getting some experience off of the service desk as well, which I can use to continue my career going forward.

      My main concern is that I am unfamiliar with contract work. I do know that I get health benefits / 401k / sick days, but I assume there must be a drawback to being a contractor, right? I feel like being a contractor is inherently more unstable than being an actual hire. The position I am being considered for is a 2 year contract, but I worry that the position could simply disappear a few months in and I'd be out of a job. Is this a fair feeling, and is there any way I can gauge how true this might be for my position? Is there something I could discreetly ask in my interview that might help me understand if this is a stable position?

      If anyone has any experience as a contractor, I'd love to hear it.

      4 votes
    13. Two-factor authentication for home VNC via Signal

      For my particular use case I share my home PC with my spouse and since I'm the more tech-savvy of the two I'll need to occasionally remote in and help out with some random task. They know enough...

      For my particular use case I share my home PC with my spouse and since I'm the more tech-savvy of the two I'll need to occasionally remote in and help out with some random task. They know enough that the issue will usually be too complex to simply guide over the phone, so remote control it is.

      I'm also trying to improve my personal efforts toward privacy and security. To that end I want to avoid closed-source services such as TeamViewer where a breach on their end could compromise my system.

      The following is the current state of what I'm now using as I think others may benefit from this as well:

      Setup

      Web

      I use a simple web form as my first authentication. It's just a username and password, but it does require a web host that supports server side code such as PHP. In my case I just created a blank page with nothing other than the form and when successful the page generates a 6 digit PIN and saves it to a text file in a private folder (so no one can simply navigate to it and get the PIN).

      I went the text file route because my current hosting plan only allows 1 database and I didn't want to add yet another random table just for this 1 value.

      Router

      To connect to my home PC I needed to forward a port from my router. I'm going to use VNC as it lets me see what is currently shown on the monitor and work with someone already there so I forward port 5900 as VNC's default port. You can customize this if you want. Some routers allow you to SSH into their system and make changes that way so a step more secure would be to leave the port forward disabled and only enable it once a successful login from the web form is disabled. In my case I'll just leave the port forwarded all the time.

      IP Address

      To connect to my computer I need to know it's external IP address and for this I use FreeDNS from Afraid.org. My router has dynamic DNS support for them already included so it was easy to plug in my details to generate a URL which will always point to my home PC (well, as long as my router properly sends them my latest IP address). If your router doesn't support the dynamic DNS you choose many also allow either a download or the settings you would need to script your own to keep your IP address up to date with their service.

      Signal

      Signal is an end-to-end encrypted messenger which supports text, media, phone and video calls. There's also a nifty command line option on Github called Signal-cli which I'm using to provide my second form of authentication. I just downloaded the package, moved to my $PATH (in my case /usr/local/bin) and set it up as described on their README. In my case I have both a normal cell phone number and another number provided by Google Voice. I already use my normal cell phone number with Signal so for this project I used Signal-cli to register a new account using my Google Voice number.

      VNC

      My home PC runs Ubuntu 18.04 so I'm using x11vnc as my VNC server. Since I'm leaving my port forwarded all the time I most certainly do NOT want to leave VNC also running. That's too large a security risk for me. Instead I've written a short bash script that first checks the web form using curl and https (so it's encrypted) with its own login information to check if any PIN numbers have been saved. If a PIN is found the web server sends that back and then deletes the PIN text file. Meanwhile the bash script uses the PIN to start a VNC session with that PIN as the password and also sends my normal cell the PIN via Signal-cli so that I can login.

      I have this script set to run every minute so I'm not waiting long after web login and I also have the x11vnc session set to timeout after a minute so I can quickly connect again should I mess something up. It's also important that x11vnc is set to auto exit after closing the session so that it's not left up for an attacker to attempt to abuse.

      System Flow

      Once everything is setup and working this is what it's like for me to connect to my home PC:

      1. Browse to my web form and login
      2. Close web form and wait for Signal message
      3. Launch VNC client
      4. Connect via dynamic DNS address (saved to VNC client)
      5. Enter PIN code
      6. Close VNC when done

      Code

      Here's some snippets to help get you started

      PHP for Web Form Processing

      <?php
      // Variables
      $username = 'your_username';
      $password = 'your_password_super_long_and_unique';
      $filename = 'path_to_private_folder/vnc/pin.txt';
      
      // Process the login form
      if($action == 'Login'){
      	$file = fopen($filename,'w');
      	$passwd = rand(100000,999999);
      	fwrite($file,$passwd);
      	fclose($file);
      	exit('Success');
      }
      
      // Process the bash script
      if($action == 'bash'){
      	if(file_exists($filename)){
      		$file = fopen($filename,'r');
      		$passwd = fread($file,filesize($filename));
      		fclose($filename);
      		unlink($filename);
      		exit($passwd);
      	} else {
      		exit('No_PIN');
      	}
      }
      ?>
      

      Bash for x11vnc and Signal-cli

      # See if x11vnc access has been requested
      status=$(curl -s -d "u=your_username&p=your_password_super_long_and_unique&a=bash" https://vnc_web_form.com)
      
      # Exit if nothing has been requested
      if [ "$status" = "No_PIN" ]; then
        # No PIN so exit; log the event if you want
        exit 0
      fi
      
      # Strip non-numeric characters
      num="${status//[!0-9]/}"
      
      # See if they still match (prevent error messages from triggering stuff)
      if [ $status != $num ]; then
        # They don't match so probably not a PIN - exit; log it if you want
        exit 1
      fi
      
      # Validate pin number
      num=$((num + 0))
      if [ $num -lt 100000 ]; then
        # PIN wasn't 6 digits so something weird is going on - exit; log it if you want
        exit 1
      fi
      if [ $num -gt 999999 ]; then
        # Same as before
        exit 1
      fi
      
      # Everything is good; start up x11vnc
      # Log event if you want
      
      # Get the current IP address - while dynamic DNS is in place this serves as a backup
      ip=$(dig +short +timeout=5 myip.opendns.com @resolver1.opendns.com)
      
      # Send IP and password via Signal
      # Note that phone number includes country code
      # My bash is running as root so I run the command as my local user where I had registered Signal-cli
      su -c "signal-cli -u +google_voice_number send -m '$num for $ip' +normal_cell_number" s3rvant
      
      # Status was requested and variable is now the password
      # this provides a 1 minute window to connect with 1-time password to control main display
      # again run as local user
      su -c "x11vnc -timeout 60 -display :0 -passwd $num" s3rvant
      

      Final Thoughts

      There are more secure ways to handle this. Some routers support VPN for the connect along with device certificates which are much stronger than a 6 digit PIN code. Dynamically opening and closing the router port as part of the bash script would also be a nice touch. For me this is enough security and is plenty convenient enough to quickly offer tech support (or nab some bash code for articles like this) on the fly.

      I'm pretty happy with how Signal-cli has worked out and plan to use it again with my next project (home automation). I'll be sure to post again once I get that ball rolling.

      13 votes
    14. Using ghoneycutt/pam puppet module

      Hi guys, I'm really stumped and looking for a nudge in the right direction for how to utilise the ghoneycutt/pam module in puppet. Relatively new to this but got what I'd like to think as most the...

      Hi guys,

      I'm really stumped and looking for a nudge in the right direction for how to utilise the ghoneycutt/pam module in puppet. Relatively new to this but got what I'd like to think as most the basics down.

      I've configured a few things using modules such as NTP, SSSD and NSSWITCH but I'm just stuck on how I can use this module and pull info from Hiera into it.

      So, lets start with

      .yaml file:

      
              ### nsswitch.conf authentication configuration
      
              nsswitch::passwd:     'files sss'
      
              nsswitch::shadow:     'files sss'
      
      
      

      And then looking at the nsswitch.pp file:

      
              ### nsswitch.config setup
      
              class profile::linux::base::nsswitch {
      
              # Get heira values
      
                class { 'nsswitch':
      
                  passwd    => [lookup('nsswitch::passwd')],
      
                  shadow    => [lookup('nsswitch::shadow')],
      
      
      

      Simple enough to call the values I want and works how I want, now I'm trying to do the same type of thing for PAM using the ghoneycutt/pam module and there doesn't seem to be much info on how to use it, or it's just not sinking in for me.

      Some of my PAM Heira values:

              pam::pam_auth_lines:
                - '# Managed by Hiera key pam::pam_auth_lines'
                - 'auth        required      pam_env.so'
                - 'auth        sufficient    pam_fprintd.so'
                - 'auth        sufficient    pam_unix.so nullok try_first_pass'
                - 'auth        requisite     pam_succeed_if.so uid >= 500 quiet'
                - 'auth        sufficient    pam_sss.so use_first_pass'
                - 'auth        required      pam_deny.so'
              pam::pam_account_lines:
                - '# Managed by Hiera key pam::pam_account_lines'
                - 'account     required      pam_unix.so'
                - 'account     sufficient    pam_localuser.so'
                - 'account     sufficient    pam_succeed_if.so uid < 500 quiet'
                - 'account     [default=bad success=ok user_unknown=ignore] pam_sss.so'
                - 'account     required      pam_permit.so'
              pam::pam_password_lines:
                - '# Managed by Hiera key pam::pam_password_lines'
                - 'password    requisite     pam_cracklib.so try_first_pass retry=3 type='
                - 'password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok'
                - 'password    sufficient    pam_sss.so use_authtok'
                - 'password    required      pam_deny.so'
      

      Some things I've tried:

      1:

              class profile::linux::base::pam {
                # resources
                class { 'pam':
                  password-auth-ac  => [
                    lookup('pam::pam_auth_lines')],
                    lookup('pam::pam_account_lines')],
                    lookup('pam::pam_password_lines')],
                    lookup('pam::pam_session_lines')],
                 }
      
      

      2:

      
      	
      	      passwd  => [
      	
      	      lookup('pam::pam_auth_lines'),
      	
      	      lookup('pam::pam_account_lines'),
      	
      	      lookup('pam::pam_password_lines'),
      	
      	      lookup('pam::pam_session_lines'),
      	
      	      ],
      	
      	  }
      
      
              include ::pam
      
      	class profile::linux::base::pam {
      	
      	  # resources
      	
      	    include ::pam
      
      	         lookup('pam::pam_auth_lines')
      	
      	}
      
      
      

      I've tried a few other ways and can't get it to work as I want it to. Can anyone help?

      Thanks

      4 votes