Reverse a string in Rust

Rust has been gaining a lot of positive attention in the developer community due to very many positive things. You can read more on Stackoverflow (https://stackoverflow.blog/2020/01/20/what-is-rust-and-why-is-it-so-popular/) so I will avoid repetition on this blog.

Rust has fantastic support for basic str primitive (https://doc.rust-lang.org/std/primitive.str.html) but there are typical things that are very hard to get a grip on when one jumps to Rust as a C/C++ developer. I was doing some exercisim.io for Rust and came across a nice exercise where a primitive str is passed to a function which is expected to return a Rust String with the contents reversed i.e. drawer as an input is reversed into reward as an out.

Exercism has quite a few test cases with widechar strings as well. I went through quite some resources but couldn’t find a simple way to use str with widechar. So I used the following solution:

pub fn reverse(input: &str) -> String {
    let mut input_vec: Vec<u16> = input.encode_utf16().collect();
    let mut output_vec: Vec<u16> = Vec::new();

    while input_vec.len() != 0 {
        output_vec.push(input_vec.pop().unwrap());
    }
    
    return String::from_utf16(&output_vec).expect("Found invalid UTF-16");
}

I converted the str into a u16 vector and a while loop poping from one vector and pushing to another (Playground link: https://gist.github.com/rust-play/49a036d0f96c6795756e58b809fa6a8b). I guess another option would be to use a reverse iterator. I am unsure if this is the most optimum way of doing things. I am looking forward to your comments.

Google CTF – Quest 3 (High-Speed Chase)

This is the first quest where you are told to write code in JavaScript. It is a very easy challenge to clear and tests the basics of conditional statements. The problem is that after breaking away from the Prague Apartment (Quest 2), you are being followed by adversaries. Luckily you get your hands on a self-driving car and you can break-in into the self-driving module and write your own code to get it to move faster than the pursuers. You are also helped by data points which are collected from satellites and sent to you for use. You can use JavaScript to write the code and get away from the pursuers.

So the background story is good but the main question is are you really going to write a self-driving module code? No, you are not. Basically, you are going to code a small function that is called multiple times per second, and depending on the value returned from the function, your car will either move 1 unit left, keep going straight or 1 unit to the right. So your function returns an integer, -1 meaning move 1 unit left, 0 meaning keep going straight, and 1 meaning move 1 unit right. The array of 17 data points is passed as input to the function. The more value of a particular data point, the more is the distance of an obstacle from that data point.

So basically your data will look like something below.

arr[0] = 10, arr[1] = 11….. arr[16]=3

The values at a particular point indicate the distance from the obstacle up ahead. There is also a picture IIRC to show how the data points might plot out. More information is in the quest of course. The real question is how will you interpret this data and move the car around so you don’t hit any obstacles and go ahead safely.

Your algorithm needs to make sure that the center point of the car is always pointing to the longest distance possible in the array values. Since there are 17 markers, if the center point of the car is the longest at the center, keep going straight, if it is less than half (i.e. 8) go left otherwise go right. Pretty easy right? This is a typically find min/max in an array problem.

So basically we keep tracking a center point to the maximum value of the array and note down the index. If the index is less than 8, go left, if 8, go straight, and if more than 8, go right. This simple logic works because the function is called multiple times in a second (i.e. at a higher frequency). If it would only be called once per move, the logic will fail and we will need more advanced techniques but for this quest, the simple algo suffices.

Below is the code for the same. As usual, I will not provide direct answers. I have some deliberate easy errors in the code which you can fix to get through this module.

    var maxDist = scanArray[0];
    var center = 0;
    for (let i = 1; i <= 16; i++) {
        if (scanArray[i] >= maxDist) {
            maxDist = scanArray[i];
        }
            center = i - 1;
    }

    if (center == 8) {
        return 0;
    } else if (center < 8) {
        return 0;
    } else {
        return 0;
    }

Enjoy and don’t forget to leave your comments below. See you for the next quest.

Google CTF – Quest 2 (Prague Apartment)

Quest 2 is even easier than Quest 1 (if you have studied logic gates). Basically, the idea is to go through the circuit given and arrive at the code which will provide for a 1 on the final output. The combination of gates that are TRUE needs to be mentioned in CTF{<answer>}. The rest of the gates can be ignored.

There is a very simple way to solve it. We do a reverse traversal from the final gate to the input gates. The idea is to basically have the final value as true and then look at the gates input. Determine the input values so that the final value is true. Do the reverse traversal in an iterative fashion until one reaches the inputs defined.

Another option is to draw the circuit in a logic gate simulator like logic.ly and then toggle the switches to get the final output (true) on the end gate. This is brute force method but again can be cracked quite easily. I suggest doing the reverse traversal first before doing the brute force method. The logic diagram looks like below:

I have deliberately turned off some switches so as to hide the real answer. But there you are, it should be very easy to solve. Do write in your comments if you have done it or not. Next would be the 3rd one if I get some time this week. Keep the fun rolling in :).

Google CTF (Beginners Quest)!

I have been doing reverse engineering (RE) since my childhood days and that always helps freshen up my technical skills as well as understand the intrinsic working details of a particular piece of code and/or software. I have used tools such as IDA, x64dbg/Ollydbg, hiew, and more recently Ghidra. In the past I had also used SoftICE and quite a few other things. Those were the golden days when one can play around and I had all the time to learn stuff.

But these days, it is hard to find time to indulge into the RE scene. In the weekend, I was getting bored and didn’t have anything to do. So just took a shot at Google CTF (https://capturetheflag.withgoogle.com/). It is a good resource to have fun and learn stuff. Click on the BeginnersQuest ((https://capturetheflag.withgoogle.com/beginners-quest)) and you would be presented with a (complex) map. There is a 1 on Side B top right corner. Click on it and you should be taken to the first challenge (https://cctv-web.2021.ctfcompetition.com/). The first challenge is to crack the password for getting access to those CCTV cameras!

The idea is to hack the password. If done properly, you should see 4 CCTV cameras and a CTF{<string>}. This is the string that you need to submit to finish the challenge. I will not paste the CTF string here so don’t ask for it. But this first challenge is pretty easy to solve. Right-click on the page and view the source of the page. Look at the checkPassword() function in Javascript embedded in the HTML page.

The function is pretty easy to understand. There are a bunch of unicode characters compared for the password. It is a byte by byte comparison. And I have given the solution now. It is very easy to implement in Javascript and get the password.

If you are still confused, have a look at the solution here: https://onecompiler.com/javascript/3z3vj2v9n

BTW: Could have been solved with python, C and a host of other languages. I just chose JS as it was hosted and pretty easy to script in there.

Hope you all got started on Google CTF. I will hopefully find time for the next challenge and will put a write-up soon.

Home Alarm in Sweden

Home Alarm (Hemlarm in Swedish) systems market in Sweden is pretty monopolistic with 2 big companies (Verisure and Sector Alarm) dominating the home alarm market. Alarm systems needs to be connected to the central alarm system which is the one monitoring and calling in emergency services (Police & fire departments) in case of break-ins or fire. HomeAlarm systems from the big companies can cost as much as 500 SEK per month. In many cases, I have seen people spending more than 600 SEK per month.

All the alarm systems used by the security companies are pretty basic and most are Zigbee / ZeeWave systems. One needs to cuff up around 10K SEK for the instruments, plus installation charges of roughly 2.5K SEK before they get started on the 500 SEK monthly premiums. Information on home alarm systems, costs, etc. is pretty scattered on the internet so I thought of compiling the information on a single page which could help me and everybody else who is looking to save some bucks by cutting the crap.

I was thinking of changing my alarm system and did some pretty good research across on how the alarm systems market and home insurance is tied up and connected. In Sweden, there are certain rules that one needs to be aware of.

  1. Insurance companies give a 5% discount if one has an alarm system connected to the central alarm system
  2. Police insists that alarm systems can be a deterrent for possible burglary attempts
  3. In case of an ongoing burglary, Police will only come if the person calling is present onsite i.e. If one has an indoor security camera and can see the burglary happening, the Police will not come if the person calling is not present around the place of incidence

So installation of an alarm system connected to the central alarm is a must if one wants peace of mind and have a comparative safety net. Now, connection to the central alarm system would basically cost around 145 SEK per month. So my ultimate aim is to find ways to reduce the monthly as well as initial cost. Below is my analysis of different companies.

  1. Verisure – The biggest company in this business. It has its own central alarm system and has somewhat decent devices connected. But these are locked systems and the more devices you have, the higher monthly premium cost. Initial costs, installation and monthly premium make it a very high-cost alternative. Verisure does not have any binding period but has a 3 month notice period to break the contract instead.
  2. Sector Alarm – Similar to Verisure, these guys are the 2nd biggest in Sweden with a similar cost structure even though they don’t run their own central alarm system. Instead, they use the ones provided by Securitas, Nokas, etc. So another high-cost alternative. I think Sector Alarm has a binding period of 24 months but I didn’t really catch it from the sales guy.

If you are going with any of the above, it is time to rethink. Below are some better alternatives providing the same or better services at a lower cost.

  1. Alert Alarm – These guys are a part of Verisure. Yes, now how many of you knew it? The devices used are different and only includes an IR sensor instead of “Camera with IR sensor”. But that is a minor point. Besides they use the Verisure infrastructure at an amazing lower cost. Price point for Alert is 300 SEK per month. They also allow for self installation thus resulting into saving of professional installation costs. The devices itself are not that costly and the binding period is only 24 months.
  2. Securitas – If one is really interested to go with big names, I STRONGLY recommend Securitas. The equipment provided by them is relatively new Zigbee gateway and devices. Plus they do not charge extra for any added devices which is the right thing to do. In all other companies, the more devices you have connected, the higher the cost. With Securitas, you just pay for the devices (which are reasonably priced), add as many as you like, and pay a monthly fee of 300 SEK. They have their own infrastructure which is also used by other companies.
  3. Garda Alarm – These guys are another good small players in the market. With good negotiation skills, one can land somewhere between 350-400 SEK per month premium. They use Lövestads central alarm system as well as Nokas, Securitas, etc.
  4. Svenska Alarm – Svenska Alarm by far has the most advanced devices for home security on the market. These guys are a bit costly if you go on the monthly premium but you can simply buy the equipment up front and then pay only 145 SEK per month for the security services and connection to the central alarm system. The devices are a bit on the price side so if I was asked to select between Svenska and Securitas, I would go with Securitas.

There are other smaller companies like Gardio, SikkertHem, Protexus, WeBeHome, etc. are smaller players that either provide their own services or sells devices and asks to be setup with central alarm systems for fees ranging from 80 SEK to 200 SEK per month. So no real cost advantage and hence am not discussing those in detail. One particular mention is Safeland which allows for pretty newer devices to be bought and connect to central alarm systems. As an aside, if you have the Imou Cell Pro, you can already connect those with safeland central alarm system for 800 SEK per year. Now that is very cheap and a good investment since you have the latest and greatest in home security!

Hope you are able to do a proper comparison and save some bucks. Beware of the tricky alarm sales people :).

Cheers