First of all, what is fanfiction?  Well, fanfiction is a genre of sorts.  The name says it all.  It is where fans of a book or movie take the book's (or movie's) plot, characters, and/or any other elements and make a story of their own.  The author of the fanfiction story may make up their own characters to go in it, or just use the already created characters.  Yes, it is legal, as long as you don't publish or sell your fanfiction story.