Friday 28 January 2022

Reset your Azure Ubuntu VM Password

I created an Ubuntu VM in Azure some months ago and when this week I decided to connect to it again I realised that I could not find my password (I mean the password for my user in that Ubuntu VM, not my Azure account password). Oddly enough, there's not an option in the Azure portal or an Azure CLI command to directly reset the VM password, you'll have to do it through several steps.

First point is enable login to the VM using a ssh key. So you need a ssh key pair (generated with ssh-keygen -f ./myKey -t rsa) and then you have to run an Azure CLI command to upload the public key to the VM:
az vm user update -u myUserName --ssh-key-value "myPublicKeyContentHere" -g resourceGroup -n VMName

The command will upload the public key to your $HOME/.ssh/authorized_keys folder in the VM, so now you can login to the VM using:
ssh -i myKey.priv myUser@myVM

That's good, and probably using the ssh key to login is more convenient than using a regular password, but anyway I wanted to be able to use a password also. Once you log to the machine, if you try to change your forgotten password with passwd, you'll be asked for the old password, so what?

Well, that's simple, the salted hash of the different user's passwords is stored in the /etc/shadow file and you can edit it as super user with "su". You'll see one line like this for your user:

myUser:$6$gYiiiiiiiiiiiiiiiiiiiy0$uJ6Eu9IwZ/gggggggggggggggggggggggggggg.vgBol0j0HT1Z0Kxmg46AbVTIn0G4cKazzhhhhhhhhhhhh0yWF1:19019:0:99999:7:::

The second item in that line is your hashed password. Delete it (I mean, the password, not the whole line), and now your user has an empty password. If you run again the passwd command you won't be asked for the old (empty) password, and you can set your new password.

Python Bound-Methods and Monkey-Patching

After almost 14 years without hardly any contact with Python (just some occasional reading) I'm coming back to it. In the last years for any scripting needs I'd been sticking to nodejs, but I've recently been assigned to a project at work that uses Python 3, so I'm already trying to get up to date with it.

I've found out today about "bound methods" that I think did not exist in Python 2, and work in an interesting way. I'll compare in this post method invocation in Python and JavaScript, and monkey-patching.

In Javascript, when we invoke a method (either a method defined in a class, and hence added to the class.prototype, or a function directly attached to an instance), I mean:


class Person{
	constructor(name){
		this.name = name;
	}

	sayHi(){
		console.log("Bonjour, je m'appelle " + this.name);
	}
}

let p1 = new Person("Francois");
p1.sayHi();

p1.saySomething = function(msg){console.log(this.name + " vous dit " + msg);};
p1.saySomething();


what is happening in each call are 2 things: first, we lookup the sayHi or saySomething function in the p1 object (its prototype chain... vous savez...) and then, javascript invokes that function passing as this the p1 object on which the look up has been done. The function has a "dynamic this".

Additionally, if the function obtained in the lookup already were bound to a "this" value (either cause it's the result of a Function.prototype.bind or because it's an arrow function), it will be invoked with the bound "this" (static this)

Python 3 works a bit differently, as it comes with the concept of bound methods and the descriptor protocol. Invoking a method also involves 2 steps. First, looking up the function in the object, and then calling that retrieved function. The difference is that if the retrieved function is in the class, what we obtain is a "bound method", as it comes with the object on which the lookup has been done bound as first parameter (there is not "this" notion in Python, we use the "self" convention to refer to the first parameter passed in a function call)


class Person:
    def __init__(self, name, lastName):
        self.name = name
        self.lastName = lastName

    def getFullName(self):
        return self.name + " " + self.lastName

p1 = Person("Francois", "Arboleya")


gFN2 = p1.getFullName
print(gFN2)
#gFN2 is a bound method (0x000001C4338B5FD0 is p1):
#<bound method Person.getFullName of <__main__.Person object at 0x000001C4338B5FD0>>
#so I don't have to pass the person instance, it's already bound
print(gFN2())


This means that if we just attach a function to an object, we have a different behaviour from the one in javascript. The lookup will return the function, not a "bound method", so we can not expand (monkey-patch) an object properly that way.


def fullNameWithFormat(p):
    return "[[" + p.name + " " + p.lastName + "]]"

#monkey-patching the instance is problematic
p1.fullNameWithFormat1 = fullNameWithFormat
#because the lookup returns the function, not a bound-method
print(p1.fullNameWithFormat1)
#<function fullNameWithFormat at 0x000001FA6DC6E040>

try:
    print(p1.fullNameWithFormat1())
except BaseException as err:
    print(f"- Unexpected {err=}, {type(err)=}")
    #TypeError: fullNameWithFormat() missing 1 required positional argument: 'p'

However, we can fix this by means of types.MethodType (that works more or less like Function.prototype.bind). We create a bound method that we can attach to the object instance.


#to monkey-patch the instance we have to do this:
p1.fullNameWithFormat2 = types.MethodType(fullNameWithFormat, p1)
print(p1.fullNameWithFormat2)
#bound method:
#<bound method fullNameWithFormat of <__main__.Person object at 0x0000017CCC9B5FD0>>
print(p1.fullNameWithFormat2())

Notice that for monkey-patching the class, we can just attach a function to the class, and then doing a look-up in an instance will return a bound method


#monkey pathing the class works fine
Person.fullNameWithFormat3 = fullNameWithFormat
print(p1.fullNameWithFormat3)
#bound method
#<bound method fullNameWithFormat of <__main__.Person object at 0x0000017CCC9B5FD0>>
print(p1.fullNameWithFormat3())


Tuesday 25 January 2022

Invoke JavaScript Constructor

I've been revisiting how we've been able to create an object of an arbitrary type in JavaScript over the years. I mean, a function that receives the "Type" (that is, a function intended to work as a constructor) and the arguments and creates an instance of that "Type". In current JavaScript it's really simple (thanks to the rest-spread operators)


function createFromType1(type, ...args) {
        return new type(...args);
}

//or

function createFromType2(type, ...args) {
        return Reflect.construct(type, args);
}

class Person{
	constructor(name, age){
		this.name = name;
		this.age = age;
	}
}

let p1 = createFromType1(Person, "Francois", 4);
let p2 = createFromType2(Person, "Francois", 4);



But in the past it was quite a bit more complicated, so I've felt like doing a bit of Javascript Archeology and writing it down here (I still consider useful to have an understanding of these things).

The first thing to understand is what happens when we call a function with new (either an ES6 class constructor or a normal function that we invoke with new). Remember that arrow functions and ES6 class methods are not constructible (can not be invoked with new). From this StackOverflow answer:

The new operator takes a function F and arguments: new F(arguments...). It does three easy steps:

Create the instance of the class. It is an empty object with its __proto__ property set to F.prototype. Initialize the instance.

The function F is called with the arguments passed and this set to be the instance.

Return the instance

(regarding the "instance of the class" there's a slight difference between a ES6 constructor and a normal function invoked with new, I talked about it in this post, but is not particularly important

Before ES5, to replicate the 3 aforementioned steps we had to do something like this (from the same StackOverflow answer):


    function New (f) {
/*1*/  var n = { '__proto__': f.prototype };
       return function () {
/*2*/    f.apply(n, arguments);
/*3*/    return n;
       };
     }
     
let p1 = New(Person)("Francois", 4);

or like this:


function construct(type, args) {
    function F() {
        type.apply(this, args);
    }
    F.prototype = type.prototype;
    return new F();
}
let p1 = construct(Person, ["Francois", 4]);

With the advent of ES5 we could simplify it a bit using Object.create, like this:


function createFromType(type, args){
	return type.apply(Object.create(type.prototype), args);
}
let p1 = createFromType(Person, ["Francois", 4]);

The 3 techniques above will not work with ES6 classes, because we can not use "apply" (or "call") with an ES6 class constructor (it's only constructable, but not callable, so using call or apply will throw an "Uncaught TypeError: Class constructor xxx cannot be invoked without 'new'"). So we can just forget about them (safe for historical reasons) and use the 2 first approaches that I show in this post.

Saturday 22 January 2022

Open Ports

On several occasions lately I've not been able to start a server application cause I already had another "forgotten" process listening on that port. I'll write here the steps to locate and kill that initial process.

Windows. I want to kill the process listening on port 3000. Using standard Windows tools (no need to install some bash version or anything) we can use "netstat -ano" to list TCP and UDP listening ports and established connections, and then do some filtering on the output, like this:
netstat -ano | fidstr LISTENING | findstr 3000 to get the process ID
and then taskkill /F /PID 12345 to kill the process (with PID 12345)

Linux. netstat is considered deprecated in most Linux distros and we should use the ss command instead.
We can use "ss -ltunp" to list TCP and UDP listening ports, and then do some filtering on the output, like this:
ss -ltunp | grep LISTEN | grep 3000 to get the process ID
and then kill -9 12345 to kill the process (with PID 12345)

I had almost forgotten that UDP is a connectionless protocol and somehow this seems to have motivated netstat and ss authors to display a different State value for listening UDP ports. netstat shows TCP listening ports as "LISTENING" status, and UDP ports as empty. ss shows TCP listening ports as "LISTEN" and UDP ports as "CONN".