Network Share Login via C#

Accessing remote share programmatically from Windows is easy. Just use \\machine\share notation and you’re golden. Except if you need to access it with a specific user. While PrincipalContext can often help, for samba shares hosted by Linux, that doesn’t necessarily work.

bool Login(string path, string user, string password) {
  var nr = new NativeMethods.NETRESOURCE {
    dwType = NativeMethods.RESOURCETYPE_DISK,
    lpRemoteName = path
  };
  var result = NativeMethods.WNetUseConnection(IntPtr.Zero, nr, password, name, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
  return (result == NativeMethods.NO_ERROR);
}

And, of course, we also need our definitions:

private static class NativeMethods {
    internal const Int32 NO_ERROR = 0;
    internal const Int32 RESOURCETYPE_DISK = 0x00000001;

    [StructLayout(LayoutKind.Sequential)]
    internal class NETRESOURCE {
        public Int32 dwScope = 0;
        public Int32 dwType = 0;
        public Int32 dwDisplayType = 0;
        public Int32 dwUsage = 0;
        public IntPtr lpLocalName;
        public String lpRemoteName;
        public IntPtr lpComment;
        public IntPtr lpProvider;
    }

    [DllImport("mpr.dll", CharSet = CharSet.Ansi)]
    internal static extern Int32 WNetUseConnection(
        IntPtr hwndOwner,
        NETRESOURCE lpNetResource,
        String lpPassword,
        String lpUserId,
        Int32 dwFlags,
        IntPtr lpAccessName,
        IntPtr lpBufferSize,
        IntPtr lpResult
    );

}

And that should be enough for access.

DNS over HTTPS for Mikrotik

Illustration

With everything moving to HTTPS, there’s still one component that gets overlooked - DNS. Most of time lookups are still done via essentially plain-text protocol. And it’s not for the lack of encrypted alternatives as there are at least three different ways of doing it: DNS over HTTPS (DoH), DNS over TLS (DoT), and DNSCrypt. When it comes to Mikrotik, choice narrows a bit and only DNS over HTTPS is supported.

Realistically, DoH is enough. DoT might be a bit more elegant implementation at a lower OSI layer but both clients and public servers seem to prefer DoH due to it’s heavy reliance on HTTPS layer ubiquitous to pretty much any application these days. DNSCrypt never got off the ground and we pretty much can ignore it.

So, today’s task is to set Mikrotik router to use DNS over HTTPS lookups.

To start it all off, we first need to download CA certificate store. And yes, we could skip this step and simply not check certificates but I feel that leaves too much space for man-in-the-middle attach. Downloading one file every few years will not kill anybody.

/tool fetch url=https://curl.se/ca/cacert.pem
      status: finished
       total: 199KiB
    duration: 1s

/certificate import file-name=cacert.pem passphrase=""
     certificates-imported: 128``
     private-keys-imported: 0
            files-imported: 1
       decryption-failures: 0
  keys-with-no-certificate: 0

With certificates in place, we get to setup DNS over HTTPs.

/ip dns
set use-doh-server=^^https://cloudflare-dns.com/dns-query^^ verify-doh-cert=yes

And that’s it. To verify it working, you can visit https://1.1.1.1/help and look for “Using DNS over HTTPS (DoH)” line.


That said, one could notice one glaring issue - we still have our original DNS servers listed. And I personally do this intentionally as a fallback method. However, that does leak a bit of information and, if someone blocks our DNS resolver, can force plain-text legacy lookups.

To harden system a bit, first we need to add static entries for DNS IPs (you can find them out with nslookup cloudflare-dns.com).

/ip dns static
add name=cloudflare-dns.com address=^^2606:4700::6810:f8f9^^
add name=cloudflare-dns.com address=^^2606:4700::6810:f9f9^^
add name=cloudflare-dns.com address=^^104.16.248.249^^
add name=cloudflare-dns.com address=^^104.16.249.249^^

With static entries in place, we can clear the legacy DNS servers.

/ip dns
set servers=""

And, if we’re using DHCP, we need to disregard DNS IPs provided by upstream too.

/ip dhcp-client
set 0 use-peer-dns=no

/ipv6 dhcp-client
set 0 use-peer-dns=no

And now all DNS lookups done by router are done using DoH and nothing else.

Battery Pack Load

Illustration

Powering device via USB has its advantages even if device doesn’t need connectivity. Most notable of those advantages is a wide availability of USB battery packs. That makes powering device really easy. However, what if your device uses so little power that batter pack keeps turning off?

All three battery packs I had available had the same issue. Put something that pulls just a trickle of current and they would turn off. One of them did have a trickle-charge functionality and that sorta worked but required manual intervention. And yes, I forgot to turn it on more times than I care to remember.

So I went looking for solution and found Dorkbot PDX article by Paul. The way how he solved this issue was quite a nice one. Just put intermediate load on the bus and you’re golden. Instead of going with his solution, I decided to use my favorite hammer - Microchip PIC microcontroller - to make my own board using the same concept.

Realistically, there’s no reason to use microcontroller for this. Having a programmable part just introduces assembly complexity and you cannot use it out of box, without programming it first. But there are advantages too. The major one being adjustability and that came in really handy when figuring out the timings needed. Instead of dealing with large value capacitances, one can use inherit time keeping mechanisms of microcontrollers. Furthermore, it also allowed for easy placing of blinky light. And who doesn’t love those?

The whole solution is based on a small 6-pin PIC10F200 microcontroller. When you discount programming pins, that leaves you one pin to work with. And yes, you can pretty much use programming pins too (3 of them) if you use a few extra passives but I generally leave them alone if I can. Fortunately, application I had in mind was simple enough to solve with a single pin.

Illustration

The device logic is as simple as it gets. To keep the battery pack turned on, it uses MOSFET to pull 200 mA over two resistors for about 20 milliseconds. Once pulse is sent, wait for 10 seconds. Rinse-repeat. On all packs I’ve tried this combination worked flawlessly. Of course, if there’s a pack where this doesn’t work, adjustment is easy enough (yes, I will update code with some constants later :)).

The heavy lifting is done by MOSFET driven directly by microcontroller. Once turned on, it will allow two resistors to dissipate a bit over 200 mA of current. While this seems like a significant amount of power to pass over puny 0805 resistors, short duration means they will never get hot enough to present a problem.

One could also take an offense to how MOSFET is driven too. Due to the nature of the beast a lot of current will flow out of the gate pin and by common knowledge one has to have a resistor to limit it. However, this MOSFET is small enough that current limiters built-in to Microchip PIC microcontrollers are fine. I had even bigger MOSFETs work in circuit for years without gate resistor so I am not too worried. That said, if I ever change to different microcontroller, some reevaluation will be needed.

And yes, there is no bleed-off resistor on MOSFET gate either. If circuit is powered on, PIC will be driving it either low or high so pulling the MOSFET gate down is not really needed. If circuit is not powered on, who cares - there’s no power to go around anyhow. That leaves only the short amount of time when circuit is powered on and PIC is not yet driving the gate. And that is the interval we can safely ignore as it’s shorter than 20 milliseconds and even erroneously active MOSFET will cause no damage to the circuit in that time.

Thanks to Microchip’s semi-standard pinout, this device can use any number of PIC microcontrollers. As long as footprint fits (SOT23-6), you’re golden. I have tried it with already mentioned PIC10F200 and PIC10F320 but any variant should work too. Yes, the firmware did need a bit of adjusting between methuselah PIC10F200 and newish PIC10F320 but those were simple enough. In these times of chip shortages, having multiple parts fit is always a nice thing.

Illustration

How much battery this uses, you might ask. It would be a bit annoying to have your battery drained by a device whose only purpose is to keep it awake. Well, to start with, we need to account for all power usage. The main one is of course our 220 mA pulse (5V/(47Ω÷2)) lasting 20 milliseconds. Since it repeats every 10 seconds, that leads us to a duty cycle of 0.2%. Multiply one by another and we can see that average power usage is about 0.5 mA.

Second power user is our LED that blinks with the pulse. Due to large value resistor, it will require slightly less than 1 mA for each pulse. Using our duty cycle, that us average consumption of 2 µA (0.002 mA). Pretty much a noise compared with our load.

And lastly there’s the PIC itself. Good news is that this is well under 1 mA. How much under? I have no idea as I didn’t have anything capable of measuring it. I will definitely need to create a board for that too. However, I did use USB power meter to get a long term reading of the usage and it was slightly under 0.5 mA (averaged over an hour) if using PIC10F320. For older PIC10F200 usage is a smidgen above it.

Those reading more carefully might wonder, if a power pulse needs about 0.5 mA, and total consumption is under 0.5 mA, we have the free energy as microcontroller is actually using the negative power from a far dimension to run itself. Sadly, it’s not so. Due to how MOSFET is driven, it won’t turn on nor it will turn off instantly. So our 200 mA pulse average will actually be lower. And PIC consumption is low enough to “hide” in those numbers.

Code actually runs constantly in the background due to a quirk of PIC10F200. If you put it in sleep, it resets itself (by design) making it annoying to keep track of time longer than 2.3 seconds. I was toying with idea of just using the newer PIC10F320 but power usage of constantly running PIC was low enough that I decided not to care.

Either way, if you have 10000 mAh battery, this device could theoretically run for 20000 hours. Suffice it to say that it shouldn’t reduce battery life too much. If you really want to squeeze the last possible mAh out of it, you could adjust timings. For example, my Anker power bank was quite happy with more than a minute between pulses (0.033% duty cycle). However the default 0.2% duty cycle is probably a good starting point when it comes to compatibility.

Lastly, there are actually two versions of the device. The “normal” one just plugs in USB port while pass-through has a female USB connector on it allowing it to be used on battery packs with a single type A output. You can find gerbers for both on GitHub alongside with the source files.

Dealing with part shortage - Microchip edition

Illustration

For a small electronics project of mine, I needed literally only one output pin. My go-to part for these situations is PIC10F200. It’s a 6-pin SOT-23 device offering internal oscillator and not much more. Microcontrollers don’t really get smaller/simpler than this.

Due to the hamster habits I have, I actually had enough enough parts to finish up the prototype so the only thing left was to order a few more parts of DigiKey. Well, as many components lately, my favorite PIC was out of stock.

However, when one door closes, another one opens. Microchip is really good at keeping pinout similar over multiple microcontrollers. And DigiKey had PIC10F202, PIC10F206, PIC10F220, PIC10F222, and PIC10LF322 available in stock. While all these PICs are slightly different, they share the same basic pinout. And for my project any of them would do. Even if I used some less common feature, Microchip often has multiple products differing only in memory amount.

While hardware might be similar enough, firmware does have significant differences - especially between older PIC10F206 and newer PIC10LF322 setup. Even turning LED on/off uses different registers between them. Instead of having different firmware for each, one can make use of compiler directives and check which PIC is actually being used. Something like this:

#if defined(_10F200) || defined(_10F202) || defined(_10F204) || defined(_10F206)
    GP2 = 0;                // turn off GP2
    TRISGPIO = 0b11111011;  // GP2 is output
#else
    LATAbits.LATA2 = 0;    // turn off RA2
    TRISAbits.TRISA2 = 0;  // RA2 is output
#endif

While out-of-stock syndrome has hit Microchip too, with a bit of care, they do make transition feasible if not always trivial.

Adding USB to A-BFastiron SS-305MP

Illustration

I needed a cheap power supply for a project and it was easy to find a nice one in A-BFastiron SS-305MP. It was small enough, looked good, and had shiny display. What could man want more?

Well, when I got it and saw cutout for USB, I know what more I wanted. An USB port.

And strangely enough once you open the power supply, you’ll find connector providing about 8.2 V already there without anything to plug into. It’s almost as if somebody placed it there to be an input for 5V linear voltage converter and then later figured electronics and heatsinking would cost too much and covered the hole. And yes, it’s a proper hole cover that you can remove - no drilling necessary.

If you open power supply you will even find standoffs already in place. It’s simply begging to have PCB mounted in.

First thing to figure out was which USB connector will fit. Searching on DigiKey found quite a few of them roughly matching the dimensions. So I just selected the cheapest one that matched standard footprint. And yes, looking on side you might find it protruding a bit too much but not criminally so. It might be original designers were fine with this or the had a custom length connector in mind. For me this was as good as it gets.

With connector found, it was time to figure PCB. And I decided to keep it really simple. The whole setup would revolve around VXO7805-1000. It’s a nice DC-DC switching regulator that will take any input higher than 8 V and drop it down to 5 V with some efficiency. In its pinout it emulates beloved LM7805 but at 90% efficiency and without all the heat.

Regulator itself requires just two capacitors and I decided to go just with them. I was tempted to add a smaller 1 µF capacitor to output and maybe even a 100 nF one for decoupling purposes but decided against it. Due to wide variety of cables and outputs USB device might face, all of them already have more than sufficient decoupling and adding more wouldn’t really do anything. So why waste a component.

The only really unneeded components would be an LED and its accompanying resistor. While they serve no function, I really love to have an indicator of output. If there was ever an issue, looking at LED would at least tell me if power is going out. And quite often that’s quite a big help.

Speaking of power going out, I don’t consider a fuse optional. It’s a minimum you need in this setup. Another thing I would consider bare minimum for power supply would be a short-circuit detection but that’s fortunately already a part of voltage regulator. And yes, I could have gone further, especially by adding reverse polarity protection to the input and I was tempted but in reality you’ll just connect this thing once and leave it connected. As long as you connect it correctly the first time, you’re good.

Illustration

Connecting all this to the power is entrusted to any JST-XH 2-pin cable - 10 cm in length. Just make sure that the negative wire is going next to COM marking on the power supply motherboard. If in doubt, just double-check with voltmeter.

And that’s it. For a few bucks more and some extra soldering, we have a nice 500 mA USB port at the front of the power supply. Just in case we need it.

On GitHub you’ll find source files and releases with gerbers and part list.